我正在尝试编写一个程序来匹配文件中的正则表达式。我文件的初始行如下所示
Alternate Take with Liz Copeland (Day 1) (12am-1am)
Saturday March 31, 2007
No. Artist Song Album (Label) Comment
buy 1 Tones on Tail Go! (club mix) Everything! (Beggars Banquet)
buy 2 Devo (I Can't Get No) Satisfaction Anthology: Pioneers Who Got Scalped (Warner Archives/Rhino)
我匹配文件第一行的代码如下
with open("data.csv") as my_file:
for line in my_file:
re_show = re.compile(r'(Alternate Take with Liz Copeland) \((.*?)\)\s\((.*?)\)')
num_showtitle_lines_matched = 0
m_show = re.match(re_show, line)
bool(m_show) == 1
if m_show:
num_showtitle_lines_matched += 1
show_title = m_show.group()
print("Num show lines matched --> {}".format(num_showtitle_lines_matched))
print(show_title)
它应该给我以下结果
Alternate Take with Liz Copeland (Day 1) (12am-1am)
num_showtitle_lines_matched -->1
但是我的结果没有显示任何输出。 请让我知道如何完成此操作。谢谢。
答案 0 :(得分:1)
如评论中所示:
只需将num_showtitle_lines_matched = 0
放在循环上方:
with open("data.csv") as my_file:
num_showtitle_lines_matched = 0
for line in my_file:
re_show = re.compile(r'(Alternate Take with Liz Copeland) \((.*?)\)\s\((.*?)\)')
m_show = re.match(re_show, line)
bool(m_show) == 1
if m_show:
num_showtitle_lines_matched += 1
show_title = m_show.group()
print("Num show lines matched --> {}".format(num_showtitle_lines_matched))
print(show_title)
输出:
Num show lines matched --> 1
Alternate Take with Liz Copeland (Day 1) (12am-1am)