用python正则表达式提取非scii字符的单词

2024-07-08 07:07:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想提取一些包含非ASCII字符的文本。问题是程序将非ASCII视为分隔符! 我试过了:

regex_fmla = '(?:title=[\'"])([:/.A-z?<_&\s=>0-9;-]+)'
c1='<a href="/climate/cote-d-ivoire.html" title="Climate data: Côte d\'Ivoire">Côte d\'Ivoire</a>'
c2= '<a href="/climate/cameroon.html" title="Climate data: Cameroon">Cameroon</a>'
c_list =[c1, c2]
for c in c_list 
    print re.findall(regex_fmla , c)

结果是:

^{pr2}$

请注意,第一个国家是正确的,因为系列在ô中断,它应该是:

['Climate data: Côte d\'Ivoire']

我在StackOverflow中搜索,找到了一个建议使用该标志的答案re.UNICODE,但它返回相同的错误答案!在

我该怎么解决这个问题?在


Tags: datatitlehtmlasciilistregexhrefc2
3条回答

我建议使用BeautifulSoup解析html:

from bs4 import BeautifulSoup as bs

c1='<a href="/climate/cote-d-ivoire.html" title="Climate data: Côte d\'Ivoire">Côte d\'Ivoire</a>'
c2='<a href="/climate/cameroon.html" title="Climate data: Cameroon">Cameroon</a>'


for c in [c1, c2]:
    soup = bs(c, 'html.parser')
    print(soup.find('a')['title'])

有关更多链接(<a ...>),请使用.findAll()方法:

^{pr2}$

如果您需要任何具有title属性的内容:

for a in soup.findAll(title=True):
    print(a['title'])

我也建议使用BeautifulSoup,但似乎您想知道如何包含这些特殊字符,可以将正则表达式更改为:

ex = 'title="(.+?)"'

然后:

^{pr2}$

输出:

Climate data: Côte d'Ivoire

我建议用靓汤,但如果你愿意坚持:

import re

regex_fmla = '(?:title=[\'"])([\w :\':/.]+)'

c1 = '<a href="/climate/cote-d-ivoire.html" title="Climate data: Côte d\'Ivoire">Côte d\'Ivoire</a>'
c2 = '<a href="/climate/cameroon.html" title="Climate data: Cameroon">Cameroon</a>'
c_list = [c1, c2]

for c in c_list:
    print(re.findall(regex_fmla, c, flags=re.UNICODE))

我相信导致re.UNICODE不能工作的问题是显式地将表达式中的字母表定义为[A-z0-9]。如果我们将其更改为[\w],则标志将正常工作

相关问题 更多 >

    热门问题