【发布时间】:2020-05-20 23:44:06
【问题描述】:
我正在尝试在列表输入 k1_tweets_filtered['text'] 上运行函数 pre_process。
但是,该功能似乎一次只能处理一个输入,即k1_tweets_filtered[1]['text']。
我希望该函数在 k1_tweets_filtered['text'] 的所有输入上运行。
我尝试过使用循环,但是,循环只输出第一个输入的单词。
我想知道这是否是我如何将其应用于其余输入的正确方法
这是我要解决的问题,也是我目前编写的代码。
编写代码以预处理和清理所有推文
存储在变量k1_tweets_filtered、k2_tweets_filtered和k3_tweets_filtered中
函数pre_process() 产生新变量k1_tweets_processed, k2_tweets_processed
和k3_tweets_processed。
for x in range(len(k1_tweets_filtered)):
tweet_k1 = k1_tweets_filtered[x]['text']
x+=1
k1_tweets_processed = pre_process(tweet_k1)
下面是函数pre_process,但是,我知道这是正确的,因为它是给我的。
def remove_non_ascii(s): return "".join(i for i in s if ord(i)<128)
def pre_process(doc):
"""
pre-processes a doc
* Converts the tweet into lower case,
* removes the URLs,
* removes the punctuations
* tokenizes the tweet
* removes words less that 3 characters
"""
doc = doc.lower()
# getting rid of non ascii codes
doc = remove_non_ascii(doc)
# replacing URLs
url_pattern = "http://[^\s]+|https://[^\s]+|www.[^\s]+|[^\s]+\.com|bit.ly/[^\s]+"
doc = re.sub(url_pattern, 'url', doc)
# removing dollars and usernames and other unnecessary stuff
userdoll_pattern = "\$[^\s]+|\@[^\s]+|\&[^\s]+|\*[^\s]+|[0-9][^\s]+|\~[^\s]+"
doc = re.sub(userdoll_pattern, '', doc)
# removing punctuation
punctuation = r"\(|\)|#|\'|\"|-|:|\\|\/|!|\?|_|,|=|;|>|<|\.|\@"
doc = re.sub(punctuation, ' ', doc)
return [w for w in doc.split() if len(w) > 2]
【问题讨论】:
标签: python list function dictionary