【问题标题】:Text preprocess function cant seem to remove full twitter hashtag文本预处理功能似乎无法删除完整的推特标签
【发布时间】:2023-02-22 01:36:48
【问题描述】:

我试图制作一个使用正则表达式从字符串中删除元素的函数

在这个例子中,给定的文本是 '@twitterusername 今天狂风不观鸟#Python'

我想让它看起来像 '今天​​狂风不观鸟'

相反,如果仍然包含主题标签 '今天​​狂风没有观鸟蟒蛇'

我尝试了几种不同的模式,但似乎无法正确使用代码

`def 过程(文本): processed_text = []

wordLemm = WordNetLemmatizer()

# -- Regex patterns --

# Remove urls pattern
url_pattern = r"https?://\S+"

# Remove usernames pattern
user_pattern = r'@[A-Za-z0-9_]+'

# Remove all characters except digits and alphabet pattern
alpha_pattern = "[^a-zA-Z0-9]"

# Remove twitter hashtags
hashtag_pattern = r'#\w+\b'



for tweet_string in text:
    
    # Change text to lower case
    tweet_string = tweet_string.lower()
    
    # Remove urls
    tweet_string = re.sub(url_pattern, '', tweet_string)
    
    # Remove usernames 
    tweet_string = re.sub(user_pattern, '', tweet_string)
    
    # Remove non alphabet
    tweet_string = re.sub(alpha_pattern, " ", tweet_string)
    
    # Remove hashtags
    tweet_string = re.sub(hashtag_pattern, " ", tweet_string)
    
    
    tweetwords = ''
    for word in tweet_string.split():
        # Checking if the word is a stopword.
        #if word not in stopwordlist:
        if len(word)>1:
            # Lemmatizing the word.
            word = wordLemm.lemmatize(word)
            tweetwords += (word+' ')
        
    processed_text.append(tweetwords)
    
return processed_text`
    
    
    

【问题讨论】:

    标签: python regex


    【解决方案1】:

    问题是您删除了主题标签之前的非字母字符。这意味着“#”不再出现在输入字符串中,因此主题标签无法被识别。你应该扭转这些:

     # Remove hashtags
        tweet_string = re.sub(hashtag_pattern, " ", tweet_string)
     # Remove non alphabet
        tweet_string = re.sub(alpha_pattern, " ", tweet_string)
        
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-27
      • 1970-01-01
      • 1970-01-01
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多