如何打印YAML字符串的特定部分

2024-09-30 18:35:06 发布

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

我的YAML数据库:

left:
  - title: Active Indicative
    fill: "#cb202c"
    groups:
      - "Present | dūc[ō] | dūc[is] | dūc[it] | dūc[imus] | dūc[itis] | dūc[unt]"

我的Python代码:

import io
import yaml

with open("C:/Users/colin/Desktop/LBot/latin3_2.yaml", 'r', encoding="utf8") as f:
    doc = yaml.safe_load(f)
txt = doc["left"][1]["groups"][1]
print(txt)

当前我的输出是Present | dūc[ō] | dūc[is] | dūc[it] | dūc[imus] | dūc[itis] | dūc[unt],但我希望输出是ōisitimus。这在PyYaml中可能吗?如果可能的话,我将如何实现它?提前谢谢。你知道吗


Tags: importtxt数据库yamldoctitleisit
1条回答
网友
1楼 · 发布于 2024-09-30 18:35:06

我没有PyYaml解决方案,但是如果您已经拥有YAML文件中的字符串,那么可以使用Python的^{}模块来提取[ ]中的文本。你知道吗

import re

txt = "Present | dūc[ō] | dūc[is] | dūc[it] | dūc[imus] | dūc[itis] | dūc[unt]"

parts = txt.split(" | ")
print(parts)  
# ['Present', 'dūc[ō]', 'dūc[is]', 'dūc[it]', 'dūc[imus]', 'dūc[itis]', 'dūc[unt]']

pattern = re.compile("\\[(.*?)\\]")
output = []
for part in parts:
    match = pattern.search(part)
    if match:
        # group(0) is the matched part, ex. [ō]
        # group(1) is the text inside the (.*?), ex. ō
        output.append(match.group(1))
    else:
        output.append(part)

print(" | ".join(output))
# Present | ō | is | it | imus | itis | unt

代码首先将文本分割成单独的部分,然后循环遍历每个部分以获得模式[x]。如果找到它,它将从match object中提取括号内的文本并将其存储在列表中。如果part与模式不匹配(例如'Present'),它只是按原样添加它。你知道吗

最后,将所有提取的字符串^{}-ed在一起,以重新构建不带括号的字符串。你知道吗


编辑基于comment

如果只需要[ ]中的一个字符串,可以使用相同的正则表达式模式,但在整个txt上使用^{}方法,该方法将返回匹配字符串的list,其顺序与找到它们的顺序相同。你知道吗

import re

txt = "Present | dūc[ō] | dūc[is] | dūc[it] | dūc[imus] | dūc[itis] | dūc[unt]"

pattern = re.compile("\\[(.*?)\\]")
matches = pattern.findall(txt)
print(matches) 
# ['ō', 'is', 'it', 'imus', 'itis', 'unt']

然后只需使用一些变量从列表中选择一个项目:

selected_idx = 1  # 0-based indexing so this means the 2nd character
print(matches[selected_idx])
# is

相关问题 更多 >