Python 从文本文件中获取单词列表
在我的在线代码中,我不知道为什么它是错误的,我尝试了无数种不同的方法,但都不起作用。我想把它打印出来:Python 从文本文件中获取单词列表,python,list,file,Python,List,File,在我的在线代码中,我不知道为什么它是错误的,我尝试了无数种不同的方法,但都不起作用。我想把它打印出来: ['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'windo
['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']
romeo.txt是文本文档名
这是里面的内容:
“但是从那边窗户射进来的光线打破的是东方和东方
朱丽叶是太阳升起美丽的太阳,杀死嫉妒的月亮的人
已经因悲伤而生病、脸色苍白”
输出也是按字母顺序排列的
fname = "romeo.txt"#raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
lst.append(line)
words = lst.split(line)
# line = line.sort()
print lst
代码中的注释。基本上,把你的行分开,然后把它累积到你的列表中。最后应进行一次排序
一种(稍微)更具python功能的解决方案:
import re
lst = sorted(re.split('[\s]+', open("romeo.txt").read(), flags=re.M))
Regex将根据regexp(分隔符为空格)将文本拆分为单词列表。其他一切基本上都是多行压缩成1行
import re
lst = sorted(re.split('[\s]+', open("romeo.txt").read(), flags=re.M))