Python 创建一个列表文件并编写查询

Python Create a List file and write query

很抱歉我的问题看起来很简单,但我是 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])我想创建一个字典用于查询
  2. nl=[x for x in dm if x[0]=='P'] 我想写以 "P" 字母开头的单词

这是我的问题:

1.问: 我想我的 dish.py 文件有问题。我该如何重组它?

2。问: 如何对文件应用查询并提取以 "P" 开头的单词 提前谢谢你

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 模块,更改 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)
  1. Q: How can I apply a query to the file and extract the words begin with "P" Thank you so much in advance

假设您想要将每个由 space 或换行符分隔的字符串和 return 放入列表中,我会这样做:

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

所以我认为你有不止这两个issues/questions。 首先,如果你想包含 'hardcoded' lists,dicts 等等,你可能想要 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(即 dish)的创建命名空间下搜索文件中命名和包含的所有数据结构。

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

您可能还对 pickling 感兴趣(尽管有一些注意事项)。