Python csv文件中的问题和解决方案
系统如何识别设备并加载特定于设备的文件,该文件包含适当的问题和回答,例如屏幕有多少英寸。 我能够在python上实现这一点,但是我不知道如何在csv文件上实现这一点。 我有3个设备,系统应该识别,但是因为代码很长,我只显示一个设备Python csv文件中的问题和解决方案,python,csv,input,Python,Csv,Input,系统如何识别设备并加载特定于设备的文件,该文件包含适当的问题和回答,例如屏幕有多少英寸。 我能够在python上实现这一点,但是我不知道如何在csv文件上实现这一点。 我有3个设备,系统应该识别,但是因为代码很长,我只显示一个设备 用户必须能够通过输入与程序交互。我建议使用JSON格式来存储数据,这使您在如何存储数据方面具有更大的灵活性。如果您的JSON文件如下所示: { "phone": { "iphone": { "iphone6": {
用户必须能够通过输入与程序交互。我建议使用JSON格式来存储数据,这使您在如何存储数据方面具有更大的灵活性。如果您的JSON文件如下所示:
{
"phone": {
"iphone": {
"iphone6": {
"8GB": [
[
[
"keyword1",
"keyword2"
],
"solution1"
],
[
[
"keyword3",
"keyword4"
],
"solution2"
]
],
"16GB": [
...
]
},
"iphone7": {
"8GB": ...,
"16GB": ...
},
}
"samsung": ...
},
"tablet": ...
}
(…
表示您放在那里的数据)然后您可以直接使用用户输入的数据作为数据的键:
import json
# read your data from a file
with open("data.json") as f:
data = json.load(f)
# ask for device
while True:
device = input("Enter your device: ")
try:
device_data = data[device.strip().lower()]
except KeyError:
print("Please enter a valid device.")
else:
break
# ask for manufacturer
while True:
manufacturer = input("Enter the manifacturer of your device: ")
try:
manufacturer_data = device_data[manufacturer.strip().lower()]
except KeyError:
print("Please enter a valid manufacturer.")
else:
break
# ask for model
while True:
model = input("Enter your model: ")
try:
model_data = manufacturer_data[model.strip().lower()]
except KeyError:
print("Please enter a valid model.")
else:
break
# ask for memory
while True:
memory = input("Enter the amount of internal memory you have: ")
try:
memory_data = model_data[memory.strip().lower()]
except KeyError:
print("Please enter a valid amount.")
else:
break
# ask for problem
while True:
problem = input("Enter your problem: ")
words = problem.strip().lower().split(" ")
for keywords, solution in memory_data:
if set(words) & set(keywords):
print(solution)
break
else:
print("A solution could not be found, please describe your problem more clearly.")
我加入了.strip().lower()
,以使更多可能的输入有效。这接受“iphone”
、“iphone”
、“iphone”
和“iphone”
作为有效输入。为了让用户了解哪些选项是可能的,您还可以在问题中输出选项。这是制造商的一个例子:
options = list(device_data.values())
output = "Enter the manifacturer of your device ["+"/".join(options)+"]: "
manufacturer = input(output)
只有当您想对每台设备提出相同的问题时,此解决方案才有效。如果情况并非如此(例如,在谈论相机时,您不想询问用户有多少内存),那么您可以将该问题包含在JSON文件中,并递归提问。有人能帮我吗???您真的需要将信息存储在csv文件(基本上是一个表)中吗或者您可以选择如何存储数据?如果您有选择的自由,我强烈推荐JSON,因为它在层次结构中工作得更好。使用JSON,您可以将数据存储在字典中(例如,
{device1:[(关键字,解决方案),(关键字,解决方案)],device2:[(关键字,解决方案)]}
),然后根据用户输入访问数据。谢谢。我对JSON进行了研究,并试图在代码中实现它,但它不起作用。你能帮我生成代码吗。一个例子可以给我一个想法@BurningKarlCan我在记事本上使用JSON格式如果你能将JSON格式转换成记事本,它会被引用JSON只是格式化数据的一种特殊方式。它由普通文本组成,可以由任何编辑器编写和读取,包括记事本++或Microsofts记事本。(无需在数据文件末尾使用.json
,也可以将其称为data.txt
)