我正在尝试创建一个程序,该程序将根据用户的输入从CSV提取某种类型的电缆。使用该电缆,我将使用其规格来求解方程式。
我正在尝试从每条电缆制作一个字典,以便提取它并将其用于求解方程式会更加顺利。这是代码。
import csv
import math
with open("origionalconductordata.csv", "r") as file:
#read the file
reader = csv.reader(file)
cable = {}
#creating a cable dictionary
for column in reader:
cable[column[1]] = {'Stock Number':column[2], 'Overall Diameter':column[49],
'Diameter Over Conductor':column[40], 'Conductor Size': column[10]}
#Finding out what cable the user wants
def find_cable():
spec = raw_input("Type the cable Spec Number below. If you do not have a Spec Number, type 'no'.\n>")
size = raw_input("Type the size of the cable.\n>")
if spec and size in cable:
print cable[spec][size]
find_equation()
elif spec == "no":
next = raw_input("Type the Overall Diameter of the cable.\n>")
if next in cable:
print cable[next][size]
find_equation()
else:
print "Diameter not found."
find_cable()
else:
print "Unable to find request."
find_cable()
预期的结果是该代码将为您提供与用户“规格编号”和“尺寸”相匹配的电缆。利用电缆字典中的信息,可以求解方程式。在我的代码中的实际结果是,当您键入“规格编号”和“大小”时,会弹出else语句“无法找到请求”。
最佳答案
您有一个字典cable
,它以电缆规格作为键,每个键的值是对应于规格的数据字典。
如果spec and size in cable
具有与True
和cable
匹配的键,则表达式spec
将计算为size
。我认为您真的想检查spec
的值是否具有等于[cc>的“导体尺寸”的值:
if spec in cable and cable[spec]['Conductor Size'] == size:
find_equation()
在没有提供规格的情况下,您似乎正在尝试查找具有给定“直径尺寸”和正确的“导体尺寸”的电缆。由于
size
的键不是直径大小,因此,除非巧合,否则cable
永远不会为真。您需要检查next in cable
中的每个值是否符合您的要求。elif spec == "no":
# Use meaningful variable names to show your intent.
diameter_size = raw_input("Type the Overall Diameter of the cable.\n>")
# Search for matches.
for k, v in cable.items():
if (v['Diameter Size'] == diameter_size
and v['Conductor Size'] == size):
find_equation()
if next in cable:
print cable[next][size]
find_equation()
反复处理此类输入请求的通常方法是使用
cable
循环,而不是递归调用while
。因此该函数最终看起来像未经测试的代码:def find_cable():
while True:
spec = raw_input("Type the cable Spec Number below. If you do not have a Spec Number, type 'no'; type 'q' to quit.\n>")
conductor_size = raw_input("Type the size of the cable.\n>")
if spec in 'Qq':
print('Bye!')
break
if (spec in cable
and cable[spec]['Conductor Size'] == conductor_size):
find_equation()
elif spec == "no":
diameter_size = raw_input("Type the Overall Diameter of the cable.\n>")
# Search for matches.
for k, v in cable.items():
if (v['Diameter Size'] == diameter_size
and v['Conductor Size'] == size):
find_equation()
# Break out of the for loop once we find a match.
break
else:
# For loops have an else clause that is triggered if the code
# doesn't break out of the loop
print "Diameter not found."
else:
print "Unable to find request."
最后,如果有许多不同的电缆(例如1000s),则遍历所有指令以找到匹配的直径将很慢。考虑将数据加载到像sqlite这样的数据库中。
关于python - 从CSV提取信息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56061188/