regex 文本预处理功能似乎无法删除完整的twitter标签

uqjltbpv  于 2023-03-04  发布在  其他
关注(0)|答案(1)|浏览(111)

我正在尝试创建一个使用正则表达式从字符串中移除元素的函数
在这个例子中,给定的文本是“@twitterusername疯狂的风今天没有观鸟#Python”
我想让它看起来像'疯狂的风今天没有观鸟'
相反,如果仍然包括这个“疯狂的风今天没有观鸟Python”的标签
我尝试了一些不同的模式,似乎不能得到它的权利,这里是代码
'def进程(文本):已处理文本= []

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`
bf1o4zei

bf1o4zei1#

问题是你删除了标签前面的非字母字符,这意味着输入字符串中不再有'#',因此标签无法被识别。你应该反转这些字符:

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

相关问题