[英]accented characters in a regex with Python
這是我的代碼
# -*- coding: utf-8 -*-
import json
import re
with open("/Users/paul/Desktop/file.json") as json_file:
file = json.load(json_file)
print file["desc"]
key="capacità"
result = re.findall("((?:[\S,]+\s+){0,3})"+key+"\s+((?:[\S,]+\s*){0,3})", file["desc"], re.IGNORECASE)
print result
這是文件的內容
{
"desc": "Frigocongelatore, capacit\u00e0 di 215 litri, h 122 cm, classe A+"
}
我的結果是 []
但我想要的是 result = "capacità"
您需要將字符串視為 Unicode 字符串,如下所示:
str = u"Frigocongelatore, capacit\u00e0 di 215 litri, h 122 cm, classe A+"
正如你所看到的,如果你print str.encode('utf-8')
你會得到:
Frigocongelatore, capacità di 215 litri, h 122 cm, classe A+
同樣,您可以分別使用u
或r
使正則表達式字符串成為 unicode 或原始字符串。
您可以使用此功能來顯示不同的編碼。
編輯器上的默認編碼應該是 UTF-8。 使用sys.getdefaultencoding()
檢查您的設置。
def find_context(word_, n_before, n_after, string_):
# finds the word and n words before and after it
import re
b= '\w+\W+' * n_before
a= '\W+\w+' * n_after
pattern = '(' + b + word_ + a + ')'
return re.search(pattern, string_).groups(1)[0]
s = "Frigocongelatore, capacità di 215 litri, h 122 cm, classe A+"
# find 0 words before and 3 after the word capacità
print(find_context('capacità',0,3,s) )
capacità di 215 litri
print(find_context(' capacit\u00e0',0,3,s) )
capacità di 215 litri
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.