我试图将不正确的单词附加到列表中,但是当我在函数外部打印列表时,它是空的,而当我在函数内部打印它时,它会打印每个单词的列表。如何在程序结束时只打印一次包含不正确单词的列表?
文件 1: 这是我的拼写检查程序
文件 2:dis 是我的 spll cheker 程序
因此应该将 3 个不正确的单词添加到列表中
word_list = []
if cmdlength != 2:
print ("Usage error, expected 2 args got " + str(cmdlength))
exit()
else:
try:
f = open(sys.argv[1])
f.close()
except FileNotFoundError:
print("File does not exist")
exit()
try:
ff = open(sys.argv[2])
ff.close()
except FileNotFoundError:
print("File does not exist")
exit()
word = ""
with open(sys.argv[1],"r") as fh:
while True:
ch=fh.read(1)
if ch == " " or ch == "\n" or ch == ":" or ch == ".":
with open(sys.argv[2],"r") as fh2:
def check_word(word,fh2,word_list):
lines = fh2.readlines()
for line in lines:
x= re.search(word,line)
if x:
#correctwords
print(word + ": " + "0")
#count += 1
else:
#incorrect words
print(word, ": " , "1")
word_list.append(word)
#count2 += 1
check_word(word,fh2,word_list)
word = ''
else:
word += ch
if not ch:
print(word)
print("End of file")
print(word_list)
break
最佳答案
该函数缺少返回 word_list
的 return
语句。
这应该有效
...
def check_word(word,fh2,word_list):
lines = fh2.readlines()
for line in lines:
...
word_list.append(word)
#count2 += 1
return word_list
word_list = check_word(word,fh2,word_list)
关于python - 将单词添加到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59180800/