python中写文件之后为什么输出两遍_在python中使用输入和输出文件来确定重复的单词...

该Python程序旨在从一个文件中找出重复的单词,忽略标点并将它们以小写形式写入另一个文件。然而,遇到两个问题:1) 标点符号清除不彻底;2) 重复单词在目标文件中按原始文件中出现次数重复写入。代码尝试通过读写文件处理这些问题,但`break`语句未能阻止重复单词的多次写入。
摘要由CSDN通过智能技术生成

我希望我是清楚的。我正在尝试创建一个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}$

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值