删除Python中的标点符号但保留表情符号

时间:2017-06-13 14:18:41

标签: python sentiment-analysis

我正在研究情绪分析。在数据列表中,我想删除所有标点符号,以获取纯文本中的单词。但我想保留表情符号,例如:)和:/。

有没有办法在Python中说我想删除所有标点符号,除非它们出现在诸如“:)”,“:/”,“< 3”之类的组合中?

提前致谢

这是我的剥离代码:

for message in messages:
message=message.lower()
message=message.replace("!","")
message=message.replace(".","")
message=message.replace(",","")
message=message.replace(";","")
message=message.replace(";","")
message=message.replace("?","")

message=message.replace("/","")
message=message.replace("#","")

3 个答案:

答案 0 :(得分:1)

你可以试试这个正则表达式:

(?<=\w)[^\s\w](?![^\s\w])

用法:

import re
print(re.sub(r'(?<=\w)[^\s\w](?![^\s\w])', '', your_data))

Here是一个在线演示。

这个想法是匹配一个特殊字符(如果前面有一个字母)。

如果正则表达式没有按预期工作,您可以稍微自定义它。例如,如果您不希望它与逗号匹配,则可以将它们从字符类中删除,如下所示:(?<=\w)[^\s\w,](?![^\s\w])。或者,如果您要删除表情符号:-),可以将其添加到正则表达式中,如下所示:(?<=\w)[^\s\w](?![^\s\w])|:-\)

答案 1 :(得分:0)

您最好的选择可能是简单地将表情符号列表声明为变量。然后将您的标点符号与列表进行比较。如果它不在列表中,请将其从字符串中删除。

编辑:您可以尝试以下方法,而不是一遍又一遍地使用整个str.replace()块。

<Button Style="{StaticResource IconStyle}" Foreground="Green">
    <Button.Tag>
        <iconPacks:PackIconMaterial Kind="Face" Width="24" Height="24" />
    </Button.Tag>
</Button>

编辑2:

最简单的方法(技能方面)可能是尝试这个:

to_remove = ".,;:!()\"
for char in to_remove:
    message = message.replace(char, "")

再一次,这只适用于与其他字符分开的表情符号,即from string import punctuation emoticons = [":)" ":D" ":("] word_list = message.split(" ") for word in word_list: if word not in emoticons: word = word.translate(None, punctuation) output = " ".join(word_list) 但不是"Sure :D"

答案 2 :(得分:0)

使用str.replace完成您已完成的工作后,您可以执行以下操作:

lines = [
    "Sentence 1.",
    "Sentence 2 :)",
    "Sentence <3 ?"
]

emoticons = {
    ":)": "000smile",
    "<3": "000heart"
}

emoticons_inverse = {v: k for k, v in emoticons.items()}

punctuation = ",./<>?;':\"[]\\{}|`~!@#$%^&*()_+-="

lines_clean = []
for line in lines:
    #Replace emoticons with non-punctuation
    for emote, rpl in emoticons.items():
        line = line.replace(emote, rpl)

    #Remove punctuation
    for char in line:
        if char in punctuation:
            line = line.replace(char, "")

    #Revert emoticons
    for emote, rpl in emoticons_inverse.items():
        line = line.replace(emote, rpl)

    lines_clean.append(line)

print(lines_clean)

但这不是超级高效的,所以如果性能成为瓶颈,你可能想要研究如何更快地实现这一点。

输出:python3 test.py

['Sentence 1', 'Sentence 2 :)', 'Sentence <3 ']
相关问题