文件类似于:
6, 'bird', 'flies', False
需要按照以下方式订购:
{'bird': (6,'flies', False)}
这是我目前所拥有的,但没有正确格式化。
{"'bird'": '1'}
我目前的代码:
def read_info_file(filename):
d = {}
count = 0
file = open(filename, "r")
lines = file.readlines()
for line in lines:
split = tuple(line.split(","))
if count > 0:
d[split[1]] = split[0]
count += 1
return d
我也不能在这个问题中导入任何模块。
答案 0 :(得分:2)
使用Python手工解析csv
文件通常比它的价值更多。以下是一种解析单个行,使用生成器,同时仍使用csv
模块的简单方法:
<强>代码:强>
import csv
def parse_my_csv(csv_file):
for line in csv_file.readlines():
# replacing comma/space with comma
yield line.replace(", ", ",")
with open('myfile.csv', 'rU') as csvfile:
csv_read = csv.reader(parse_my_csv(csvfile), quotechar="'")
for row in csv_read:
d = {row[1]: (int(row[0]), row[2], bool(row[3]))}
print(d)
<强>结果:强>
{'bird': (6, 'flies', True)}
答案 1 :(得分:1)
以下内容会根据您的格式要求格式化csv。
代码:
导入csv
来自pprint import pprint
def filter(str):
str = str.strip().strip("'")
return str
def read_info_file(filepath):
try:
res = {}
csvfile = open(filepath,'r')
csv_reader = csv.reader(csvfile)
for row in csv_reader:
res[filter(row[1])] = (int(row[0]),filter(row[2]),bool(row[3]))
except Exception as e:
print("Exception occurred: " + str(e))
finally:
csvfile.close()
return res
res = read_info_file('file.csv') pprint(RES)
<强>输出:强>
{'animal':( 7,'苍蝇',真), 'bird':(6,'苍蝇',真), '昆虫':(8,'苍蝇',真)}
答案 2 :(得分:0)
要在没有任何导入模块的情况下执行此操作,您可以使用以下理解:
<强>代码:强>
def read_info_file(filename):
with open(filename, 'rU') as f:
return {row[1]: (int(row[0]), row[2], bool(row[3]))
for row in [
[c.strip().strip("'") for c in line.split(',')]
for line in f.readlines()
]}
<强>测试强>
print(read_info_file('myfile.csv'))
<强>结果:强>
{'bird': (6, 'flies', True)}