1

我正在尝试自动执行一系列查询,但是,我需要用相应的 html 实体替换带有重音符号的字符。它需要在 Python3 中

例子:

vèlit 
[needs to become] 
vèlit

问题是,每当我尝试做 aword.replace时,它都找不到。

这个:

if u'è' in sentence:
    print(u'Found è')

工作并找到“è”,但这样做:

word.replace('è','è')

什么都不做。

4

3 回答 3

2

您可以使用str.translate方法和 python 的html包中的数据将字符转换为等效的 html 实体。

为此,str.translate需要一个将字符(技术上是字符的整数表示,或ordinal)映射到 html 实体的字典。

html.entities.codepoint2name包含所需的数据,但实体名称不受“&”和“;”的限制。您可以使用 dict 理解来创建包含所需值的表。

创建表后,以表为参数调用字符串的 translate 方法,结果将是一个新字符串,其中任何具有等效 html 实体的字符都将被转换。

>>> import html.entities
>>> s = 'vèlit'

>>> # Create the translation table
>>> table = {k: '&{};'.format(v) for k, v in html.entities.codepoint2name.items()}

>>> s.translate(table)
'vèlit'

>>> 'Voilà'.translate(table)
'Voilà'

请注意,带重音的拉丁字符可能由 unicode 代码点的组合表示:“è”可以由单个代码点表示 - LATIN SMALL LETTER E WITH GRAVE - 或两个代码点 - LATIN SMALL LETTER E后跟COMBINING GRAVE ACCENT。在后一种情况下(称为分解形式),翻译将无法按预期工作。

为了解决这个问题,您可以使用Python 标准库中unicodedata模块中的normalize函数将两个代码点分解形式转换为单个代码点组合形式。

>>> decomposed
'vèlit'
>>> decomposed == s
False
>>> len(decomposed)    # decomposed is longer than composed
6
>>> decomposed.translate(table)
'vèlit'
>>> composed = unicodedata.normalize('NFC', decomposed)
>>> composed == s
True
>>> composed.translate(table)
'vèlit'
于 2018-05-12T09:37:52.370 回答
2

替换word.replace('è','è')word = word.replace('è','è')并打印结果以进行检查。

word.replace('è','è')确实有效,但实际上并没有对word内容本身进行任何更改。

检查str.replace()

于 2018-05-10T19:03:24.880 回答
1

作为对蛇字符集提供的答案的更新,了解 Python 3.3 引入了html.entities.html5将更多字符映射到等效的 Unicode 字符可能会有所帮助。

对我来说,我需要那本字典,因为codepoint2name没有包含ł.

因此,创建转换表的代码稍微更改为:

table = {get_wide_ordinal(v): '&{}'.format(k) for k, v in html.entities.html5.items()}

get_wide_ordinal我从https://stackoverflow.com/a/7291240/1233830得到的:

def get_wide_ordinal(char):
    if len(char) != 2:
        return ord(char)
    return 0x10000 + (ord(char[0]) - 0xD800) * 0x400 + (ord(char[1]) - 0xDC00)

因为html5查找中的某些字符是两个字节宽。

请注意,此表中的 HTML5 实体确实以 a 结尾,;这就是从格式字符串中删除它的原因。

于 2021-05-04T13:20:16.880 回答