因此,出于某种原因,这个问题突然出现了,我不知道为什么会发生。
当我改变了打开文件的方式之后,它就开始出现了,但是我一点也不知道为什么会影响它,因为对象不像.我已经想了大概一个小时了,但没有结果。
import re
def get_words_from_file(filename):
"""gets words from file and applies reg expression (brokey)"""
with open(filename, 'r', encoding="utf-8") as file:
all_lines = [line.strip() for line in file]
bound_start = 0
bound_end = 0
bound_num = 0
for line in all_lines:
bound_num = bound_num + 1
if "*** START" in line:
bound_start = bound_num
elif "*** END" in line:
bound_end = bound_num
else:
pass
print(bound_start, bound_end)
bound_num = 0
pre_re_list = []
for line in all_lines:
bound_num = bound_num + 1
if bound_num in range(bound_start, bound_end):
pre_re_list.append(line)
else:
pass
print(pre_re_list)
bound_num = 0
final_list = []
for j in pre_re_list:
word_on_line = re.findall("[a-z]+[-'][a-z]+|[a-z]+[']?|[a-z]+", pre_re_list[bound_num])
bound_num = bound_num + 1
final_list.append(word_on_line)
return final_list
filename = "abc.txt"
words2 = get_words_from_file(filename)
print(filename, "loaded ok.")
print("{} valid words found.".format(len(words2)))
print("Valid word list:")
print("\n".join(words2))
我开始收到这条错误消息,如果有人能告诉我为什么/如何修复它,那就太好了:
abc.txt loaded ok.
2 valid words found.
Valid word list:
*** RUN TIME ERROR(S) ***
Traceback (most recent call last):
File "__source.py", line 50, in <module>
print("\n".join(words2))
TypeError: sequence item 0: expected str instance, list found
发布于 2022-06-10 03:19:26
当你使用re。就像这里的word_on_line = re.findall("[a-z]+[-'][a-z]+|[a-z]+[']?|[a-z]+", pre_re_list[bound_num]
,您不能直接将列表插入表达式,首先必须将其转换为字符串。希望这能有所帮助
https://stackoverflow.com/questions/72557879
复制相似问题