2017-06-04 64 views
0

所以對於我的問題很抱歉,如果它看起來很容易,但我是python的新手用戶,我無法找到解決它的方法。Python創建一個列表文件並寫入查詢

我有一個「dish.py」文件,其中包括一些子列表

Fruits={"Ap":Apple 
     "Br":Black Mulberry 
     "Ch":Black Cherry 
     } 
Meals={"BN":Bean 
     "MT":Meat 
     "VG":Vegetable 
     } 
Legumes={"LN":Green Lentil 
     "P": Pea 
     "PN":Runner Peanut 
     } 

我想在教學貫徹守則的dish.py文件在最後,我想裏面創建一個查詢該文件的

with open("/home/user/Py_tut/Cond/dish.py", 'r') as dish: 
      content = dish.read() 
print dish.closed 
dm=dict([dish]) 
nl=[x for x in dm if x[0]=='P'] 
for x in dm: 
    x=str(raw_input("Enter word:")) 
    if x in dm: 
     print dm[x] 
    elif x[0]==("P"): 
     nl.append(x) 
     print .join(nl) 

它可能看起來很混亂,但

  1. dm=dict([dish])我想創建一個字典闕RY
  2. nl=[x for x in dm if x[0]=='P']我想寫的話開始的 「P」 字母

這裏是我的問題:

1.問:我想有一個與我dish.py文件有問題。我如何重新組織它?

2.問:我如何申請查詢該文件並提取單詞,「P」開頭 非常感謝你提前

+1

你爲什麼要在內存中讀取你的'dish.py'文件,而不是讓Python解釋器爲你解析它? (當然,除了定義的'dict'是用錯誤的語法編寫的,但是爲什麼當它不應該是Python文件時將它稱爲'dish.py') – zwer

+0

我根本不知道如何,這就是爲什麼我寫了一個非常糟糕的形狀。我從頭開始瞭解如何解析等,謝謝你的評論 –

回答

1

dict()無法加載字符串:

>>> dict("{'a': 1, 'b': 2}") 
Traceback (most recent call last): 
File "<pyshell#0>", line 1, in <module> 
    dict("{'a': 1, 'b': 2}") 
ValueError: dictionary update sequence element 0 has length 1; 2 is required 

作序這將是("{", "'", "a", "'", ":",...

相反,我會用json MOD請更改dish.py格式(將擴展名更改爲.json並使用JSON語法)並更改代碼。

dish.json

{ 
    "Fruits": { 
    "Ap": "Apple", 
    "Br": "Black Mulberry", 
    "Ch": "Black Cherry" 
    }, 
    "Meals": { 
    "BN": "Bean", 
    "MT": "Meat", 
    "VG": "Vegetable" 
    }, 
    "Legumes": { 
    "GL": "Green Lentin", 
    "P": "Pea", 
    "PN": "Running Peanut" 
    } 
} 

__init__.py

import json 
with open("/home/user/Py_tut/Cond/dish.py", 'r') as dish: 
    content = dish.read() 
print(dish.closed) 
dm = json.loads(content) # loads JSON 
nl=[x for x in dm if x[0]=='P'] 
for x in dm: 
    x = str(raw_input("Enter word:")) 
    if x in dm: 
     print dm[x] 
    elif x[0] == ("P"): 
     nl.append(x) 
     print "".join(nl) 
  • Q:怎樣可以應用查詢文件並提取以「P」開頭的單詞非常感謝您提前
  • 假設你想通過空間或換行分隔每個字符串,並將其退回到一個列表,我應該這樣做:

    import re #Importing RegExp module 
    
    def wordsBeginP(): 
        with open("words.txt") as wordsfile: # Querying a file 
        words = wordsfile.open 
    
        parsed = re.sub(r"\n", " ", words) # Replace \n to " " 
        return [for i in parsed.split(" ") if i[0] == "P"] # Return list of words 
    
    +0

    非常感謝你糾正我的名單。我嘗試導入JSON,可能是因爲缺乏知識,我有一些問題,但這些給我一點,寫腳本時應該去哪裏。您的查詢解決方案也很棒,它啓發我。感謝您的寶貴貢獻。 –

    1

    所以我認爲你有比這兩個問題/疑問。首先,如果你想包括'hardcoded'list s,dict s等,你可能想要include dishdish.py在你的工作目錄中。

    也就是說,如果在Python文件中的數據結構實際上是在correct form

    Fruits={"Ap":'Apple', 
         "Br":'Black Mulberry', 
         "Ch":'Black Cherry' 
         } 
    Meals={"BN":'Bean', 
         "MT":'Meat', 
         "VG":'Vegetable' 
         } 
    Legumes={"LN":'Green Lentil', 
         "P":'Pea', 
         "PN":'Runner Peanut' 
         } 
    

    最後,你可以在所有的命名和包含在文件中的數據結構進行搜索,創建命名空間下include(這是碟子)。

    for f in [dish.Fruits,dish.Meals,dish.Legumes]: 
        for k,v in f.items(): 
        if k.startswith('P'): 
         print k,v 
    

    也有趣的你可能是pickling(雖然有一些警告)。

    +0

    非常感謝您爲我的雜亂清單付出努力。我是一個新用戶,甚至我不知道列表的正確形式。給我提供正確的表單非常棒。順便說一下,我嘗試將第二部分也用於我的代碼以進行搜索。 –