簡體   English   中英

匹配任意玩家名稱

[英]Matching arbitrary player names

我正在使用雲雀,但不知道如何匹配所有玩家的名字,因為他們可能對雲雀規則很復雜?

示例模式是"Seat {number}: {player} ({chips} in chips)" ,我也想要每一行的所有值。

from lark import Lark, lexer
gram = r"""
start: seats+

seats: "Seat " seat_position player table_chips is_sitting_out? SPACE? NL
seat_position: NUMBER
is_sitting_out: " is sitting out"
table_chips: "(" chips " in chips"  (", " chips " bounty")? ")"
player: STRING_INNER
chips: "$"? (DECIMAL | NUMBERS)

NUMBERS: /[0-9]/+
NUMBER: /[0-9]/
DECIMAL: NUMBERS "." NUMBERS
SPACE: " "+
STRING_INNER: ": " /.*?/ " " 

CR : /\r/
LF : /\n/
NL: (CR? LF)+
"""
data = r"""Seat 1: Ruzzka(Rus) (1200 in chips)
Seat 1: Dladik Rzs38 (1200 in chips)
Seat 1: slum ^o_o^ (1200 in chips)
Seat 1: é=mc² (1200 in chips)
Seat 1: {’O_0`}/(nh) (1200 in chips)
Seat 1: °ÆND0c42Z4y° (1200 in chips)
Seat 1: $ salesovish (1200 in chips)
"""
parser = Lark(gram)
tree = parser.parse(data)
print(tree.pretty())

問題是名稱結尾顯然沒有真正的規則,因此很難解析它,因為 Lark 大多是非回溯高速的。

我實際上猜想直接在每一行上使用正則表達式會更容易,除非您還需要解析比您在此處顯示的更復雜的結構。 但是 Lark 能夠處理這種任意內容, 例如 here ,但性能損失很大。

這里沒有百靈鳥的解決方案:

import re

regex = re.compile(r"Seat\s*(?P<number>\d+)\s*:\s*(?P<player>[^\n]+?)\s+\((?P<chips>\d+) in chips\)")

seats = []
for line in data.splitlines():
    match = regex.match(line)
    if match is not None:
        values = match.groupdict()
        seats.append((values["number"], values["player"], values["chips"]))

print(seats)

從您的語法看來,您實際上需要提取更多信息(例如is_sitting_outbounty )。 為此,您可以將正則表達式稍微更改為:

Seat\s*(?P<number>\d+)\s*:\s*(?P<player>[^\n]+?)\s+\((?P<chips>\d+) in chips\s*(?:,\s*(?P<bounty>\d+)\s*bounty)?\)(?P<is_sitting_out> is sitting out)?

您可以通過values['is_sitting_out'] is not None檢查玩家是否坐在外面,如果沒有賞金,則values['bounty']將為 None。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM