簡體   English   中英

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

[英]How do I print a specific part of a YAML string

我的 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)

目前我的 output Present | dūc[ō] | dūc[is] | dūc[it] | dūc[imus] | dūc[itis] | dūc[unt] Present | dūc[ō] | dūc[is] | dūc[it] | dūc[imus] | dūc[itis] | dūc[unt] Present | dūc[ō] | dūc[is] | dūc[it] | dūc[imus] | dūc[itis] | dūc[unt]但我希望 output 為ōisitimus 這在 PyYaml 中是否可行,如果可以,我將如何實現它? 提前致謝。

我沒有 PyYaml 解決方案,但如果您已經擁有 YAML 文件中的字符串,您可以使用 Python 的regex模塊來提取[ ]中的文本。

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

代碼首先將文本拆分為單獨的部分,然后循環遍歷每個部分search模式[x] 如果找到它,它將從匹配 object中提取括號內的文本並將其存儲在列表中。 如果該part與模式不匹配(例如'Present' ),它只是按原樣添加它。

最后,所有提取的字符串都join在一起以重新構建沒有括號的字符串。


根據評論編輯

如果您只需要[ ]中的一個字符串,您可以使用相同的正則表達式模式,但在整個txt上使用findall方法,這將返回匹配字符串的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']

然后只需使用一些變量來 select 列表中的一個項目:

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

暫無
暫無

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

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