【问题标题】:Python putting all words on same linePython将所有单词放在同一行
【发布时间】:2021-03-04 15:46:38
【问题描述】:

我正在尝试删除另一个文本文件中的一些单词(位于文本文件中)。尽管我的代码似乎可以工作,但我注意到它在文本文件中的某个点停止删除单词。然后我检查了文本文件,注意到 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))

提前致谢,如果您需要更多详细信息,请告诉我。

【问题讨论】:

  • 加入\n而不是空格?
  • @Sayse 将每个单词都放在一个新行上,这不是我想要做的 :(
  • 不清楚你要做什么,尝试用理解来做这件事可能会让你比它需要的更难

标签: python arrays python-3.x python-requests


【解决方案1】:

如果您希望新文件中的每一行都分开,则需要在加入字符串后添加“\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")

替代。您可以使用writelines() 方法创建要编写的行列表并编写newFile。比如:

newFile.writelines(my_list_of_lines_to_write)

【讨论】:

    猜你喜欢
    • 2013-10-21
    • 2016-08-26
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多