Python 3.x 解析长度未知的Unicode名称
我思考这个问题有一段时间了,但似乎找不到解决办法 我使用pyparsing来解析包含事件摘要的文本文件。每个文本文件包含许多事件。每个事件在标题信息的几行之后,都会以以下格式列出多个人及其相关数据: wordinteger:username(integer-word)Python 3.x 解析长度未知的Unicode名称,python-3.x,pyparsing,Python 3.x,Pyparsing,我思考这个问题有一段时间了,但似乎找不到解决办法 我使用pyparsing来解析包含事件摘要的文本文件。每个文本文件包含许多事件。每个事件在标题信息的几行之后,都会以以下格式列出多个人及其相关数据: wordinteger:username(integer-word) word是静态的,并且始终不变 整数是任意整数 用户名可以是任何unicode字符,包括符号,也可以包括空格 我似乎无法建立一个能够处理所有这些可能性的语法。当解析奇怪的unicode字符以及空格/符号时,它会陷入困境。下面的例子
正在解析的文本文件来自我无法控制的第三方,因此无法找到更具体地构造源文件的方法。尝试使用
SkipTo
(代码使用最新的pyparsing 2.1.4运行测试功能):
给出:
# a regular line
hello 1: -fred,123 (100 hello stack overflow)
['hello', 1, '-fred,123', 100, 'hello', 'stack', 'overflow']
# a username with spaces
hello 2: my name is brent (250 hello stack overflow)
['hello', 2, 'my name is brent', 250, 'hello', 'stack', 'overflow']
# a username with non-ASCII
hello 3: äää + óóó (0 hello stack overflow)
['hello', 3, '\xe4\xe4\xe4 + \xf3\xf3\xf3', 0, 'hello', 'stack', 'overflow']
OP练习:将结果名称添加到整数和用户名中,以便更轻松地访问解析字段。谢谢您的帮助。这很有魅力。感谢您指出结果名称,这将是非常有用的。我将要添加在实施此解决方案后立即遇到的另一个问题。我不确定是否应该提出另一个问题,但这与这个问题有关,所以我现在就留在这里。
# -*- coding: utf-8 -*-
tests = """
# a regular line
hello 1: -fred,123 (100 hello stack overflow)
# a username with spaces
hello 2: my name is brent (250 hello stack overflow)
# a username with non-ASCII
hello 3: äää + óóó (0 hello stack overflow)
"""
from pyparsing import *
COLON,LPAR,RPAR = map(Suppress, ":()")
integer = pyparsing_common.integer
leading = "hello" + integer + COLON
trailing = LPAR + integer + "hello" + "stack" + "overflow" + RPAR
strip = lambda t: t[0].strip()
line = leading + SkipTo(trailing).setParseAction(strip) + trailing
line.runTests(tests)
# a regular line
hello 1: -fred,123 (100 hello stack overflow)
['hello', 1, '-fred,123', 100, 'hello', 'stack', 'overflow']
# a username with spaces
hello 2: my name is brent (250 hello stack overflow)
['hello', 2, 'my name is brent', 250, 'hello', 'stack', 'overflow']
# a username with non-ASCII
hello 3: äää + óóó (0 hello stack overflow)
['hello', 3, '\xe4\xe4\xe4 + \xf3\xf3\xf3', 0, 'hello', 'stack', 'overflow']