【问题标题】:How to ignore unicode character with regex in python 3?如何在 python 3 中使用正则表达式忽略 unicode 字符?
【发布时间】:2019-09-08 10:19:39
【问题描述】:

我正在尝试解析一个包含大量 unicode 字符的词汇表。我不想抓住这些角色,如果可能的话,我想像普通角色一样处理它们。我的数据:

en  antropologi     /ɑntrupulu¹giː/     antropologien, antropologier, antropologiene    an anthropology     01A
en  arkitektur  /ɑrkitek¹tʉːr/  arkitekturen, arkitekturerarkitekturene     an architecture     01A
ei  avis    /ɑ¹viːs/    avisa, aviser, avisene  a newspaper     01P
    Barcelona   /bɑʃe¹luːnɑ/        proper name     01M
    bare    /²bɑːre/        just, only  01M
    bare bra!   /bɑre ¹brɑː/        just fine!  01M
en  bensinstasjon   /ben¹siːnstɑˌʃuːn/  bensinstasjonen, bensinstasjoner, bensinstasjonene  a petrol station    01P

我想要两组正则表达式: 组(1):Includes all vocabulary without the last "capter-ID" 组(2):Only "capter-ID"

示例: 组(1):en antropologi /ɑntrupulu¹giː/ antropologien, antropologier, antropologiene an anthropology
组(2):01A

我尝试了以下搜索算法,这些算法在我用于调试的https://regex101.com/ 上运行良好: "(.+)(01\S)\n" 和 "(\D+)(01\S)\n" 一样有效

这是我的代码和我得到的错误:

import re

def readTemplate(filepath): #reading a file
    try:
        with open(filepath, "r") as template:
            data = template.read()
        return data
    except:
        return False

def parseData(data): #parse file data
    voc = []
    cap = []

    regexMatch = re.compile("(.+)(01\S)\n").finditer(data)
    for matches in regexMatch:
        voc.append(str(matches.group(1)))
        cap.append(str(matches.group(2)))

    return voc, cap

#-----------------------------Main Prog.-----------------------------

data = readTemplate('Vocubulary.txt') #open file
voc, cap = parseData(data) #parse Data
Traceback (most recent call last):
  File "C:/User...Vocabulary.py", line 25, in <module>
    voc, cap = parseData(data) #parse Data
  File "C:/Users...Vocabulary.py", line 15, in parseData
    regexMatch = re.compile("(.+)(01\S)\n").finditer(data)
TypeError: expected string or bytes-like object

Process finished with exit code 1

【问题讨论】:

  • 如果在def readTemplate(filepath): 正下方添加data = "" 会怎样?在parserData中,在解析前添加条件if data:。见ideone.com/ly8bLN(未测试)

标签: python regex non-unicode


【解决方案1】:

虽然代码在我的机器 (linux) 上正常运行,但您可以尝试使用 raw strings

regexMatch = re.compile(r"(.+)(01\S)\n").finditer(data)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    • 2019-04-13
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    相关资源
    最近更新 更多