python - 如何在Python中搜索一行中的字符串并提取两个字符之间的数据?

标签 python python-3.x

文件内容:

module traffic(
    green_main, yellow_main, red_main, green_first, yellow_first, 
    red_first, clk, rst, waiting_main, waiting_first
);

我需要搜索字符串“module”,并且需要提取 (.......); 之间的内容括号。

这是我尝试过的代码,我无法得到结果

fp = open(file_name)
contents = fp.read()
unique_word_a = '('
unique_word_b = ');'
s = contents

for line in contents:
    if 'module' in line:
        your_string=s[s.find(unique_word_a)+len(unique_word_a):s.find(unique_word_b)].strip()
        print(your_string)

最佳答案

您的代码存在问题:

for line in contents:
    if 'module' in line:

在这里,contents是保存文件全部内容的单个字符串,而不是字符串(行)列表或可以逐行循环的文件句柄。因此,您的line实际上不是一行,而是该字符串中的单个字符,显然它永远不能包含子字符串 "module" .

因为您实际上从未使用 line在循环中,您只需删除循环和条件,您的代码就可以正常工作。 (如果您将代码更改为实际循环行,并且 find 在这些行中,则它将不起作用,因为 () 不在同一行。)


或者,您可以使用正则表达式:

>>> content = """module traffic(green_main, yellow_main, red_main, green_first, yellow_first, 
...                red_first, clk, rst, waiting_main, waiting_first);"""
...
>>> re.search("module \w+\((.*?)\);", content, re.DOTALL).group(1)
'green_main, yellow_main, red_main, green_first, yellow_first, \n               red_first, clk, rst, waiting_main, waiting_first'

在这里,module \w+\((.*?)\);意思是

  • 这个词module后面跟着一个空格和一些字型 \w字符
  • 字面开头(
  • 捕获组 (...)与任何东西. ,包括换行符 ( re.DOTALL ),非贪婪 *?
  • 字面意义上的结束 );

group(1)获取在(非转义)(...) 对之间找到的内容

如果您希望将它们作为列表:

>>> list(map(str.strip, _.split(",")))
['green_main', 'yellow_main', 'red_main', 'green_first', 'yellow_first', 'red_first', 'clk', 'rst', 'waiting_main', 'waiting_first']

关于python - 如何在Python中搜索一行中的字符串并提取两个字符之间的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54674140/

相关文章:

Python 文件串联

python - 依赖错误: netfilterqueue installation in kali

python - Elasticsearch:相同的请求,不同的结果

python - Apache Beam Python SDK ReadFromKafka 不接收数据

python - Python Telegram Bot 中的音频段库

python - 使用 Python 和 pandas 无法正确填充 MySQL 计数器列

python - Qt: session 管理错误:不支持指定的身份验证协议(protocol)。在 Linux 上使用 Python 套接字时

python - 检查一个字典的值是否是另一个字典的键

python - Scipy.Odr 多变量回归

Python 3,ast.literal_eval(node_or_string) 中是否有任何已知的安全漏洞?