【发布时间】: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