gpt4 book ai didi

Python:如何比较变量中的unicode和unicode

转载 作者:太空宇宙 更新时间:2023-11-04 03:42:10 25 4
gpt4 key购买 nike

已解决

我解决了问题,感谢您的宝贵时间。

首先,这些是要求:

  1. 比较必须在变量内。 (比较2个变量是否包含unicode)
  2. Python 的版本必须 是 2.x ,我知道版本 3 已经解决了这个问题,但不幸的是它对我不起作用。

你好,我有一个用 python 编码的机器人,我想让它比较 2 个非英文字母 (unicode)。

我遇到的问题是,字母必须在变量中,所以我不能使用:

u'letter'

我想比较的两个字母必须在变量内。

我试过:

letter1 == letter2

它显示了这个错误: E:\bots\KiDo\KiDo.py:23: UnicodeWarning: Unicode 相等比较未能将两个参数转换为 Unicode - 将它们解释为不相等 导入系统

并且总是返回 False,即使 2 个字母相同。所以我猜这意味着我正在比较 2 个 unicode 字母。

并尝试过:

letter = unicode(letter)

但它显示此错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd9 in position 0: ordinal not in range(128)

我已经在整个 Google 上进行了搜索,但我只能找到使用 u' ' 的方法,但这不适用于变量。

谢谢。

比较代码:

word1 = parameters.split()[0]
word2 = parameters.split()[1]
word3 = parameters.split()[2]
word4 = parameters.split()[3]
word5 = parameters.split()[4]
if word1[0] == letter:
if word2[0] == letter:
if word3[0] == letter:
if word4[0] == letter:
if word5[0] == letter:
reply(type, source,u'True')

最佳答案

看,字母 ç(不以 ASCII 表示的字符)可能表示为 str 对象或 unicode 对象(也许您对 unicode 的含义有点困惑)。

此外,如果您尝试创建一个 ASCII 表中不存在的 unicode 对象,则必须传递另一个编码表:

unicode('ç')

这将引发 UnicodeDecodeError,因为 'ç' 不在 ASCII 中,但是

unicode('ç', encoding='utf-8')

会起作用,因为 'ç' 在 UTF-8 编码表中显示(可能是您的阿拉伯字母)。

您可以将 unicode 对象与 unicode 对象进行比较,就像将 str 对象与 str 对象进行比较一样,所有这些都必须正常工作。

此外,您可以将 str 对象与 unicode 对象进行比较,但如果您比较的不是 ASCII 字符,这很容易出错:'ç' 作为 str 是 '\xc3\xa7' 但作为 unicode 它只是 '\xe7' (在比较中返回 False)。

所以@Karsa 可能真的是对的。问题在于您的“变量”(在 Python 中,更好的词是对象)。您必须证明您只是在比较 str 或只是 unicode 对象。

因此,更好的代码可能是:

#-*- coding: utf-8 -*-

def compare_first_letter(phrase, compare_letter):
# making all unicode objects, with utf-8 codec
compare_letter = unicode(compare_letter,encoding='utf-8')
phrase = unicode(phrase,encoding='utf-8')
# taking the first letters of each word in phrase
first_letters = [word[0] for word in phrase.split()]
# comparing the first letters with the letter you want
for letter in first_letters:
if letter != compare_letter:
return False
return True # or your reply function

letter = 'ç'
phrase_1 = "one two three four"
phrase_2 = "çarinha çapoca çamuca"

print(compare_first_letter(phrase_1,letter))
print(compare_first_letter(phrase_2,letter))

关于Python:如何比较变量中的unicode和unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25838743/

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