【问题标题】:Apply function to all inputs of a list dictionary将函数应用于列表字典的所有输入
【发布时间】:2020-05-20 23:44:06
【问题描述】:

我正在尝试在列表输入 k1_tweets_filtered['text'] 上运行函数 pre_process。 但是,该功能似乎一次只能处理一个输入,即k1_tweets_filtered[1]['text']。 我希望该函数在 k1_tweets_filtered['text'] 的所有输入上运行。

我尝试过使用循环,但是,循环只输出第一个输入的单词。

我想知道这是否是我如何将其应用于其余输入的正确方法

这是我要解决的问题,也是我目前编写的代码。

编写代码以预处理和清理所有推文 存储在变量k1_tweets_filteredk2_tweets_filteredk3_tweets_filtered中 函数pre_process() 产生新变量k1_tweets_processed, k2_tweets_processedk3_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


    【解决方案1】:
    k1_tweets_processed = []
    for i in range(len(k1_tweets_filtered)): 
        tweet_k1 = k1_tweets_filtered[i]['text']
        k1_tweets_processed.append(pre_process(tweet_k1))
    

    当你迭代时最好使用 i,j 作为变量名,如果你有“for in range(10)”你不应该在你的循环中增加它。之前您将 k1_tweets_processed 设置为单个预处理文本,而不是创建列表并向其添加新文本。

    【讨论】:

      猜你喜欢
      • 2020-03-09
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 2019-07-29
      • 2021-02-11
      • 1970-01-01
      • 2017-11-05
      • 1970-01-01
      相关资源
      最近更新 更多