python - 从没有空格、标点符号的文本文件中创建每个单词的列表

标签 python

我有一个长文本文件(剧本)。我想把这个文本文件变成一个列表(其中每个单词都是分开的),以便我以后可以搜索它。

我现在的代码是

file = open('screenplay.txt', 'r')
words = list(file.read().split())
print words

我认为这可以将所有单词拆分成一个列表,但是我无法删除所有额外的内容,例如单词末尾的逗号和句点。我还想将大写字母设为小写(因为我希望能够以小写字母进行搜索并同时显示大写和小写字母)。任何帮助都会很棒 :)

最佳答案

这是 regular expressions 的工作!

例如:

import re
file = open('screenplay.txt', 'r')
# .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

关于python - 从没有空格、标点符号的文本文件中创建每个单词的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18135967/

相关文章:

python - Ubuntu nohup 关闭具体脚本

python - 合并 Pandas DataFrame 日期时间列

python - 属性错误 : 'module' object has no attribute 'strptime' -- Possible Bug?

python - cv2.estimateRigidTransform 最小点数?

python - 迷失在pudb命令行区

python - 在 Windows 中部署 cx_Oracle

Python 按位或

python - Jupyter Notebooks 使用 Matplotlib 打印出波浪形、扭曲的图形

python - numpy 中的一些奇怪的东西

python - Pandas 滚动删除了复杂的虚部......缺陷或特征?