【发布时间】:2020-05-05 19:48:06
【问题描述】:
我有一个这样的文本文件:
莎莉……去了……去商店!!#买了一个苹果和一个百吉饼……@@ 然后她就回家了。
如何删除所有多余的内容,例如“...”、“..”和“@”,并将单词作为列表中的项目获取?
我试过了
filename.rstrip().split()
【问题讨论】:
我有一个这样的文本文件:
莎莉……去了……去商店!!#买了一个苹果和一个百吉饼……@@ 然后她就回家了。
如何删除所有多余的内容,例如“...”、“..”和“@”,并将单词作为列表中的项目获取?
我试过了
filename.rstrip().split()
【问题讨论】:
我把你提到的内容放在一个文件中,命名为“mix_char.txt”。我添加了另外两条随机线来测试新线。以下是文件内容的外观:
Sally ... went .. to the store !!# and bought an apple and a bagel..@@ Then she went home.
Sally ... @#$#%$#%$%# went ..
to .......A Store #$%#@$in 4567downtown
然后我使用下面的 sn-p 代码来读取文件,然后使用正则表达式来完成这项工作: 考虑到您只查找由字母组成的单词:
re.sub -> 用于将一个模式替换为另一个模式
[^a-zA-Z \n]*' -> 找出所有 not 包含字母、空格和换行符的模式,并将它们替换为空(即:e:删除它们)
split : 将新创建的字符串转换为列表。
import re
with open('mix_char.txt') as fh:
str = fh.read()
print (re.sub('[^a-zA-Z \n]*','',str).split())
您可以根据需要将修改后的数据写回另一个文件。
【讨论】:
使用正则表达式。在 python 中,这是通过 re 模块完成的。
[^a-zA-Z ] 表示不是字母(或空格)的字符。您可以使用re.sub 将它们全部替换为空格:
import re
def remove_non_letters(string):
return re.sub("[^a-zA-Z] ", " ", string).split()
编辑:
用
读入文本文件with open('data.txt', 'r') as file:
string = file.read()
result = remove_non_letters(string)
result 是您要查找的列表。
【讨论】:
这应该可行:
s = "Sally ... went .. to the store !!# and bought an apple and a bagel..@@ Then she went home."
s = [i for i in s if ord(i)>=65 and ord(i)<=122 or i==" "]
print("".join(s).split()))
基本上,
【讨论】:
with open("file.txt") as file: s = file.read(),其中file.txt 是您的文本文件。