我有以下代码进入 Twitter 推文,应该处理数据,然后保存到一个新文件中。
这是代码:
#import regex
import re
#start process_tweet
def processTweet(tweet):
# process the tweets
#Convert to lower case
tweet = tweet.lower()
#Convert www.* or https?://* to URL
tweet = re.sub('((www\.[\s]+)|(https?://[^\s]+))','URL',tweet)
#Convert @username to AT_USER
tweet = re.sub('@[^\s]+','AT_USER',tweet)
#Remove additional white spaces
tweet = re.sub('[\s]+', ' ', tweet)
#Replace #word with word
tweet = re.sub(r'#([^\s]+)', r'\1', tweet)
#trim
tweet = tweet.strip('\'"')
return tweet
#end
#Read the tweets one by one and process it
input = open('withoutEmptylines.csv', 'rb')
output = open('editedTweets.csv','wb')
line = input.readline()
while line:
processedTweet = processTweet(line)
print (processedTweet)
output.write(processedTweet)
line = input.readline()
input.close()
output.close()
我在输入文件中的数据如下所示,因此每条推文都在一行中:
She wants to ride my BMW the go for a ride in my BMW lol http://t.co/FeoNg48AQZ
BMW Sees U.S. As Top Market For 2015 i8 http://t.co/kkFyiBDcaP
我的功能运行良好,但我对如下所示的输出不满意:
she wants to ride my bmw the go for a ride in my bmw lol URL rt AT_USER Ðun bmw es mucho? yo: bmw. -AT_USER veeergaaa!. hahahahahahahahaha nos hiciste la noche caray!
因此它将所有内容放在一行中,而不是像输入文件中的格式那样将每条推文放在一行中。
有人想将每条推文放在一行中吗?