嗨,我正在尝试使用find-all搜索模式,如果匹配,它将返回list。我正试图访问该列表,但出现了类似(IndexError:列表索引超出范围(的错误我写的片段如下。
return_from_findall = re.findall(regex, input)
if return_from_findall:
##trying to print the list element when list returned from finall is true##
print(return_from_finall[0])
## also trying to compare the list with another string like
if return_from_finall[0] == somestring:
print(match found)
两者都不工作
有人能帮助解决这个问题吗
我的程序:
import re
output = """
Another option is to use the name randomizer.
to randomize all the names on your list.
In this case, you arent using it as a
random name picker, but as a true name
randomizer. For example,
"""
match = 0
search_item = "Another option is to use the name randomizer"
expected_list = [
'Another option is to use the name randomizer.',
'to randomize all the names on your list.',
'In this case, you arent using it as a',
'random name picker, but as a true name',
'randomizer. For example,']
for line in output.splitlines():
line = line.strip()
print(" ################### ")
return_from_findall = re.findall(search_item, line)
print("searched line - ")
print(return_from_findall)
print("expected line - ")
print(expected_list[match])
if return_from_findall:
if return_from_findall[0] == expected_list[match]:
print("found match")
如果你想看看你有多少匹配,你可以使用以下方法:
import re
output = """
Another option is to use the name randomizer.
to randomize all the names on your list.
In this case, you arent using it as a
random name picker, but as a true name
randomizer. For example,
"""
match = 0
search_item = "Another option is to use the name randomizer"
for line in output.splitlines():
line = line.strip()
return_from_findall = re.findall(search_item, line)
if return_from_findall:
match += 1
print(f"Matches: {match}")
输出:
Matches: 1
如果您想比较expected_list
中的行,看看它们是否出现在output
字符串中,那么您可以执行以下操作:
output = """
Another option is to use the name randomizer.
to randomize all the names on your list.
In this case, you arent using it as a
random name picker, but as a true name
randomizer. For example,
"""
expected_list = [
'Another option is to use the name randomizer.',
'to randomize all the names on your list.',
'In this case, you arent using it as a',
'random name picker, but as a true name',
'randomizer. For example,']
for line in expected_list:
if line in output:
print("Found: ", line)
else:
print("Not found: ", line)
输出:
Found: Another option is to use the name randomizer.
Found: to randomize all the names on your list.
Found: In this case, you arent using it as a
Found: random name picker, but as a true name
Found: randomizer. For example,