我的输入文件包含以下列表存储为 txt 文件
[(u'#Brexit', 823), (u'#brexit', 166), (u'#Brexitchaos', 135), (u'#StopBrexit', 63), (u'#EU', 46), (u'#BREXIT', 29), (u'#DavidDavis', 28), (u'#UK', 21), (u'#Remain', 20), (u'#BrexitReports', 17)]
我想将哈希标记的单词过滤掉到新的 txt 文件中。
我的预期输出是:输出.txt
Brexit
brexit
Brexitchaos
StopBrexit
EU
BREXIT
DavidDavis
UK
Remain
BrexitReports
你可以写一个正则表达式。 "(?<=#)[^']+"
在这种情况下,这意味着as many characters as possible, after a '#' and until '
:
>>> import re
>>> text = "[(u'#Brexit', 823), (u'#brexit', 166), (u'#Brexitchaos', 135), (u'#StopBrexit', 63), (u'#EU', 46), (u'#BREXIT', 29), (u'#DavidDavis', 28), (u'#UK', 21), (u'#Remain', 20), (u'#BrexitReports', 17)]"
>>> re.findall("(?<=#)[^']+", text)
['Brexit', 'brexit', 'Brexitchaos', 'StopBrexit', 'EU', 'BREXIT', 'DavidDavis', 'UK', 'Remain', 'BrexitReports']
您只需要在字符串中读取整个文件,并将列表作为行写入新文件。
假设元组中的所有第一项都被标记了,您可以执行以下操作:
data = [(u'#Brexit', 823), ..., (u'#BrexitReports', 17)]
with open('Output.txt') as f:
for word, i in data:
# if word.startswith('#') # if there are non-hashtagged words
f.write(word.lstrip('#') + 'n')
你可以试试这个:
import ast
data = ast.literal_eval(open('filename.txt').read())
f = open('new_data.txt', 'w')
for a, b in data:
if a.startswith('#'):
f.write(a[1:]+'n')
f.close()