文件内容:
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/