簡體   English   中英

如何從python中的正則表達式創建嵌套字典?

[英]How can I create a nested dictionary from a regex in python?

我創建了一個正則表達式來搜索文本塊並提取出兩件事。 我的目標是創建一個包含以下信息的 CSV(或 Excel 文件):

  1. 一組 4 位代碼
  2. 匹配的法術效果集。

我創建了我的正則表達式,我已經測試過它並成功地將我需要的所有相關信息提取到一個巨大的文本塊中。 我最初試圖通過迭代來創建一個字典,如下所示:

WildMagic = {0000: "Target's head turns into a watermelon", 0001: "Target's head turns into a cucumber",...Number: "Effect Text"}

但是,當我將其寫入 CSV 時,我得到了兩行很長的行,其中一行包含所有 4 位代碼,另一行包含所有效果。 我可以在 Excel 中修復它,但這並不是本次練習的真正目標。 經過一些閱讀,我認為最好創建一個字典字典,以便在創建 CSV 時我可以使用數字和效果標簽為我的 CSV 創建標題。

我當前的代碼如下所示:

    WildMagic = {}
for effect in textRegex.findall(str(text.read())):
    WildMagic[effect]["item"]=effect[1]
    WildMagic[effect]["value"]=effect[3]

當我勾勒出代碼時,我的想法是這段代碼將創建字典,然后遍歷文本塊中的每個項目。 對於每個數字和效果,它將創建一個如下所示的字典條目:

{1:{"item":NUMBERS, "value":SPELL_EFFECT}, 2:{"item":NUMBERS, "value":SPELL_EFFECT}...}

這個循環能夠打印每個數字、效果對,所以我知道我錯過了一些東西。 任何幫助表示贊賞。 謝謝!

編輯:用於寫入以下 CSV 的代碼:

with open("WildMagicCSV.csv", "w") as CSVfile:
    file = csv.DictWriter(CSVfile,WildMagic.keys())
    file.writeheader()
    file.writerow(WildMagic)

編輯 2:正在讀入字典的文本如下所示。 我上面描述的初始字典中也有一個例子。 輸入如下所示:

2642 Huge volumes of ectoplasm ooze from the caster's nostrils
2643 Icy winds buffet the caster for 2d8-1 days
2644 If alive, caster is totally healed in each of the next 1d6 hours

有 10,000 個條目。

首先,如果您想保持 4 位數字,您應該將0000視為字符串。 我將假設所有數字都是字符串 -> '0000'

來自WildMagic

WildMagic = {'0000': "Target's head turns into a watermelon", '0001': "Target's head turns into a cucumber"}
wild_magic = [{'id': k, 'text': v} for k, v in WildMagic.items()]
# output
[{'text': "Target's head turns into a watermelon", 'id': '0000'}, {'text': "Target's head turns into a cucumber", 'id': '0001'}]

DictWriter那里后,您可以使用csv庫中的DictWriter

import csv

with open('result_file.csv', 'w') as _f:
    fieldnames = wild_magic[0].keys()
    writer = csv.DictWriter(_f, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(wild_magic)

暫無
暫無

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

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