[英]How to search string in a line and extract data between two characters in python?
文件内容:
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']
如果要在“(””)之间提取内容,可以执行以下操作:(但首先要注意如何处理内容):
for line in content.split('\n'):
if 'module' in line:
line_content = line[line.find('(') + 1: line.find(')')]
如果您的内容不仅在一行中:
import math
def find_all(your_string, search_string, max_index=math.inf, offset=0,):
index = your_string.find(search_string, offset)
while index != -1 and index < max_index:
yield index
index = your_string.find(search_string, index + 1)
s = content.replace('\n', '')
for offset in find_all(s, 'module'):
max_index = s.find('module', offset=offset + len('module'))
if max_index == -1:
max_index = math.inf
print([s[start + 1: stop] for start, stop in zip(find_all(s, '(',max_index, offset), find_all(s, ')', max_index, offset))])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.