【发布时间】: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`
【问题讨论】: