【问题标题】:Python text to wordlist writing to filePython文本到wordlist写入文件
【发布时间】:2018-02-07 15:06:54
【问题描述】:

我正在开发基于 txt 文件的词表生成器。 当我将输出打印到屏幕时它可以工作,但当我尝试将输出写入文件时失败。

另外,有没有办法避免在我的列表中两次插入同一个词?

import re
file = open('pg23620.txt', 'r',encoding="utf8")
# .lower() returns a version with all upper case characters replaced with lower case characters.
text = file.read().lower()
file.close()
# replaces anything that is not a lowercase letter, a space, or an apostrophe with a space:
text = re.sub('[^a-z\ \']+', " ", text)
words = list(text.split())
print(*words, sep='\n')
f = open("List.txt","a")
f.writelines(*words,sep='\n')
f.close()

【问题讨论】:

  • 请具体说明您遇到了什么样的“麻烦”。
  • 另外,一次问一个问题。 (即使它是约1,000 questions的重复。)
  • 我无法将文字打印到创建的文件中,但 Martin Evans 让我了解了主题。非常感谢大家。

标签: python string file writing


【解决方案1】:

writelines() 不允许您指定行分隔符,解决方法是使用'\n'.join() 添加行分隔符,然后使用.write()。例如:

import re

file = open('pg23620.txt', 'r',encoding="utf8")
# .lower() returns a version with all upper case characters replaced with lower case characters.
text = file.read().lower()
file.close()
# replaces anything that is not a lowercase letter, a space, or an apostrophe with a space:
text = re.sub('[^a-z\ \']+', " ", text)
words = set(text.split())  # use a set to remove duplicate words
print(*words,sep='\n')
f=open("List.txt","a")
print(words)
f.write('\n'.join(words))
f.close()

更好的布局是:

import re

with open('pg23620.txt', 'r', encoding="utf8") as f_input:
    text = f_input.read().lower()

text = re.sub('[^a-z\ \']+', " ", text)
words = set(text.split())  # use a set to remove duplicate words
print(*words, sep='\n')

with open("List.txt", "a") as f_output:
    f_output.write('\n'.join(words))

使用set() 将删除重复的单词。使用with() 后,您无需手动关闭文件,因为它是自动完成的。

【讨论】:

  • 不客气!不要忘记单击向上/向下按钮下的灰色勾号以接受答案作为已接受的解决方案。
猜你喜欢
  • 1970-01-01
  • 2016-06-28
  • 1970-01-01
  • 1970-01-01
  • 2014-10-10
  • 2014-06-16
  • 2020-08-09
  • 1970-01-01
  • 2017-05-31
相关资源
最近更新 更多