【发布时间】:2015-08-04 14:25:24
【问题描述】:
问题:从 Twitter 文本中删除超链接、数字和符号,如 ^&*$ etc。推文文件为 CSV 表格格式,如下所示:
s.No. username tweetText
1. @abc This is a test #abc example.com
2. @bcd This is another test #bcd example.com
作为python的新手,我搜索并串在一起以下代码,感谢here给出的代码:
import re
fileName="path-to-file//tweetfile.csv"
fileout=open("Output.txt","w")
with open(fileName,'r') as myfile:
data=myfile.read().lower() # read the file and convert all text to lowercase
clean_data=' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",data).split()) # regular expression to strip the html out of the text
fileout.write(clean_data+'\n') # write the cleaned data to a file
fileout.close()
myfile.close()
print "All done"
它会进行数据剥离,但输出文件格式不是我想要的。输出文本文件在一行中,如
s.no username tweetText 1 abc这是一条清理过的推文2 bcd这是另一条清理过的推文3 efg这是另一条清理过的推文
如何修复此代码以提供如下所示的输出:
s.No. username tweetText
1 abc This is a test
2 bcd This is another test
3 efg This is yet another test
我认为需要在正则表达式代码中添加一些内容,但我不知道它可能是什么。任何指示或建议都会有所帮助。
【问题讨论】:
-
你想怎么从
some text到This is a test? -
感谢 Carsten Hagemann 指出该异常。我现在已经更正了这个例子。
-
尝试为 clean_data 中的每个元素写入元素 + '\n' 或逐行读取文件并通过从行中提取 clean_data 以相同方式处理它,如果它不为空,则写入 clean_data + '\n' .