gpt4 book ai didi

python - 用 "SAD"或 "HAPPY"替换表情符号的代码无法正常工作

转载 作者:行者123 更新时间:2023-11-28 22:46:50 24 4
gpt4 key购买 nike

所以我想用“HAPPY”替换所有快乐的表情符号,反之亦然用“SAD”替换文本文件的悲伤表情符号。但是代码无法正常工作。虽然它检测到笑脸(截至目前 :-)),但在下面的示例中它没有用文本替换表情符号,它只是附加文本并且由于我似乎不理解的原因它也附加了两次。

dict_sad={":-(":"SAD", ":(":"SAD", ":-|":"SAD",  ";-(":"SAD", ";-<":"SAD", "|-{":"SAD"}
dict_happy={":-)":"HAPPY",":)":"HAPPY", ":o)":"HAPPY",":-}":"HAPPY",";-}":"HAPPY",":->":"HAPPY",";-)":"HAPPY"}

#THE INPUT TEXT#
a="guys beautifully done :-)"

for i in a.split():
for j in dict_happy.keys():
if set(j).issubset(set(i)):
print "HAPPY"
continue
for k in dict_sad.keys():
if set(k).issubset(set(i)):
print "SAD"
continue
if str(i)==i.decode('utf-8','replace'):
print i

输入文本

a="guys beautifully done :-)"              

输出(“HAPPY”来了两次,表情也没有消失)

guys
-
beautifully
done
HAPPY
HAPPY
:-)

预期输出

guys
beautifully
done
HAPPY

最佳答案

你正在将每个单词每个表情符号变成一个集合;这意味着您正在寻找单个字符的重叠。您可能最多希望使用完全匹配:

for i in a.split():
for j in dict_happy:
if j == i:
print "HAPPY"
continue
for k in dict_sad:
if k == i:
print "SAD"
continue

您可以直接遍历字典,无需在那里调用.keys()。您实际上并没有使用字典值;你可以这样做:

for word in a.split():
if word in dict_happy:
print "HAPPY"
if word in dict_sad:
print "SAD"

然后也许使用集合而不是字典。这可以简化为:

words = set(a.split())
if dict_happy.viewkeys() & words:
print "HAPPY"
if dict_sad.viewkeys() & words:
print "SAD"

使用 dictionary view在键上作为一组。尽管如此,还是使用集合会更好:

sad_emoticons = {":-(", ":(", ":-|", ";-(", ";-<", "|-{"}
happy_emoticons = {":-)", ":)", ":o)", ":-}", ";-}", ":->", ";-)"}

words = set(a.split())
if sad_emoticons & words:
print "HAPPY"
if happy_emoticons & words:
print "SAD"

如果你想从文本中删除表情符号,你必须过滤这些词:

for word in a.split():
if word in dict_happy:
print "HAPPY"
elif word in dict_sad:
print "SAD"
else:
print word

或者更好的是,结合两个字典并使用 dict.get():

emoticons = {
":-(": "SAD", ":(": "SAD", ":-|": "SAD",
";-(": "SAD", ";-<": "SAD", "|-{": "SAD",
":-)": "HAPPY",":)": "HAPPY", ":o)": "HAPPY",
":-}": "HAPPY", ";-}": "HAPPY", ":->": "HAPPY",
";-)": "HAPPY"
}

for word in a.split():
print emoticons.get(word, word)

这里我传入了当前单词作为查找键和默认值;如果当前单词不是表情符号,则打印单词本身,否则打印单词 SADHAPPY

关于python - 用 "SAD"或 "HAPPY"替换表情符号的代码无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26969747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com