Python将所有单词放在同一行上

2024-10-02 12:22:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试删除另一个文本文件中的一些单词(位于文本文件中)。虽然我的代码似乎可以工作,但我注意到它在文本文件中的某个位置停止删除单词。然后我检查了文本文件,注意到Python将所有单词都写在同一行上,这一行有字符限制,导致进程停止。我怎样才能避免这种情况

这是我的密码:

# text file list to array

with open('function_words.txt') as functionFile:
    functionWords = [word for line in functionFile for word in line.split()]

# delete the word on the text file if it matches one of the array

with open("results.txt", "r+") as newfile: 
    newfile.write(' '.join(i for i in toPrint.read().split() if i not in functionWords))

提前谢谢,如果你需要更多的细节,请告诉我


Tags: thetextintxtforaswithopen
1条回答
网友
1楼 · 发布于 2024-10-02 12:22:49

如果希望新文件中的每一行都分开,则需要在加入字符串后加上“\n”。注意下面的+ "\n"

with open("results.txt", "r+") as newfile: 
    newfile.write(' '.join(i for i in toPrint.read().split() if i not in functionWords)+ "\n")

alt.您可以创建要写入的行的列表,并使用writelines()方法写入newFile。比如:

newFile.writelines(my_list_of_lines_to_write)

相关问题 更多 >

    热门问题