我希望我是清楚的。我正在尝试创建一个Python程序,它遍历第一个文件并确定哪些单词是重复的。为了确定单词是否重复,文件内容必须去掉标点符号,并且必须是小写。完成后,程序将重复的单词写入第二个文本文件。重复的单词只能在第二个文件中写入一次。在
下面,我尝试了一下,遇到了两个错误。在
错误一:我注意到创建的标点符号条函数并没有完全删除所有标点符号。在
错误二:重复出现的单词被写入第二个文件夹的次数与它们在原始文件夹中出现的次数相同。如果单词已经存在,我试图使用break函数,但是它不知怎么地绕过了break函数。在
下面是我的代码。在def repeatWords(filename_1, filename_2):
infile_1=open(filename_1,'r')
content_1=infile_1.read()
infile_1.close()
import string
content_1=content_1.strip(string.punctuation) # this did not remove all punctuations
content_1=content_1.lower()
content_1=content_1.split()
outfile=open(filename_2,'w')
outfile.write('') #used to create second file, assuming it does not exist
outfile.close()
outfile=open(filename_2,'r+')
write_content=outfile.read()
for word in content_1:
write_content=outfile.read()
if content_1.count(word)>1:
if word in write_content:
break
else:
outfile.write(word)
outfile.write('\n')
outfile.close()
# after this is executed, the words repeat as many times as they appear
infile_2=open(filename_2,'r')
content_2=infile_2.read()
infile_2.close()
return content_2
inF = 'catInTheHat.txt'
outF = 'catRepWords.txt'
print(repeatWords(inF, outF))
第一个文件中的内容是:
^{pr2}$