【问题标题】:Unicode vs ASCII - Issue processing strings with functions in string and re modulesUnicode vs ASCII - 使用字符串和 re 模块中的函数处理字符串
【发布时间】:2015-10-24 10:56:31
【问题描述】:

我正在使用 string 和 re 模块来处理文本(在句子中查找带条纹的单词)以解决 Python 2.7 中 checkIO 的问题。当我在我的计算机上运行我的 python 脚本时,我没有收到任何错误。

text = "My name is ..."

import re, string

init_word_list = re.findall('[A-z0-9]+', text)

word_list = []

for k in init_word_list:
    print type(k), repr(k)
    if str.isdigit(k):
        word_list.append(k)
    else:
        pass

但是,当我在 checkIO 上运行相同的代码时,我收到以下 TypeError。

TypeError: descriptor 'isdigit' requires a 'str' object but received a `'unicode'`

您可能已经注意到,我确实插入了 type() 和 rep() 来确定 python 在那时读取我的字符串的内容。这是输出:

<type 'unicode'> u'My'

我想知道,如果我做错了什么。另外,我有什么选择来解决这个问题?在运行 str.isdigit() 函数之前,我应该从 unicode 转换为 ASCII 吗?或者,我应该使用 re 模块进行字母检查吗?我冒昧地猜测,人们会将我指向 checkIO 论坛,以了解为什么他们的程序处理脚本的方式与在我的计算机上运行的 python 不同,但如果有人也理解这一点.. 太好了。 :)

【问题讨论】:

    标签: regex string python-2.7 unicode ascii


    【解决方案1】:

    我确实找到了解决上述问题的方法,方法是使用 encode("ascii", "ignore"),并将上述代码的一部分替换为以下代码:

    for k in init_word_list:
        l = k.encode("ascii", "ignore")
        if str.isalpha(l):
            word_list.append(k)
        else:
            pass
    

    通过花一些额外的时间谷歌搜索,我了解到 ascii 是 unicode 字符的子集 (link)。由于 checkIO 只为我提供 ascii 子集中的字符,所以我的转换没有问题。我想在进行这种类型的转换时应该小心。

    【讨论】:

      猜你喜欢
      • 2011-11-09
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      • 1970-01-01
      • 1970-01-01
      • 2015-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多