gpt4 book ai didi

python - 从 python 中的一行中拉出特定的子字符串

转载 作者:太空宇宙 更新时间:2023-11-03 13:49:47 26 4
gpt4 key购买 nike

我有一个包含许多行的文件,格式如下:

DIV ID=0X78800009 EXT="LOS ANGELES"TY=STANDARD OWN=0X74400002 ABBR=LA

我需要提取 EXT 值,但只提取引号中的部分。我目前正在使用这个:

for line in file:
if sub in line:
extlist.append([item[4:] for item in line.split() if item.startswith('EXT=')].pop())

但它只将 LOS ANGELES 的“LOS”部分附加到 idlist。我对 python 有点陌生,但是有没有办法将 item[4:] 包装在 str(item[4:]) 中并使用 string functions提取我需要的值(value)?

请注意,EXT 字段中的文本长度各不相同,它们都是随机的城市名称。

最佳答案

Regular Expressions

>>> import re
>>> myString = 'DIV ID=0X78800009 EXT="LOS ANGELES" TY=STANDARD OWN=0X74400002 ABBR=LA'
>>> re.search('EXT="(.+?)"',myString).group(1)
'LOS ANGELES'

关于python - 从 python 中的一行中拉出特定的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11886815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com