Python去除井号符号并保留关键词

6

我希望去除连接词('#')和单词间的下划线('_')。

例如:"this tweet is example #key1_key2_key3"

我想要得到的结果是:"this tweet is example key1 key2 key3"

我的代码使用字符串:

#Remove punctuation , # Hashtag Symbol 
translate_table = dict((ord(char), None) for char in string.punctuation)   
cleaned_combined_tweets.translate(translate_table)

这将产生结果:"这个推文是示例关键词1关键词2关键词3"


2
replace 方法有什么问题? - JustCarty
5个回答

4
>>> "this tweet is example #key1_key2_key3".replace("#", "").replace("_", " ")

1

首先将所有的哈希标签去掉,因为它们在开头,然后将所有下划线替换为空格;简单易行的解决方案。

修改后的代码:

string = "This tweet is example #key1_key2_key3"
string = string.strip("#")
string = string.replace("_"," ")
print(string)

1
我认为 str.strip 只能在字符串的开头和结尾起作用。 - pylang
说实话,如果你只是想把它删掉,这比使用replace更短,所以我用了两次它而不是replace。 - PythonUser
返回一个去除前导或尾随字符的字符串副本。我认为你错了。 - PythonUser
@PythonUser,你的解决方案无效,strip会删除在strip函数中出现的任何字符与单词开头或结尾匹配的字符。 - cyberbemon
有时候找到真相需要耐心。我鼓励你继续下去。寻找新的解决方法。祝你好运。 - pylang
显示剩余5条评论

0

您可以使用re模块:

import re

a = 'this tweet is example #key1_key2_key3 sdasd #key1_key2_key3'

def get_all_hashtags(text):
    hash_pattern = re.compile('\#[\w\_]+',re.IGNORECASE)
    return re.findall(hash_pattern,text)

def clean_hashtags(hashtag, return_list=False):
    # return_list just in case you want a list
    if return_list:
        return re.split('\_',hashtag.replace('#',''))
    else:
        return ' '.join(re.split('[\_]+',hashtag.replace('#','')))

print([clean_hashtags(h,True) for h in get_all_hashtags(a)])
print([clean_hashtags(h) for h in get_all_hashtags(a)])

0
假设只有 # 和 _ 作为标点符号:
import re

tweet = "this tweet is example #key1_key2_key3"
new_tweet = " ".join(word.strip() for word in re.split('#|_', tweet))
print (new_tweet)

Out: 'this tweet is example key1 key2 key3'

0
你可以使用 re 模块:
a = re.sub('([#])|([^a-zA-Z])',' ',a )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接