[英]How do I make a specifically formatted dictionary from a csv file?
I've looked around on the internet but I haven't found anything that works.我在互联网上环顾四周,但没有找到任何有效的方法。 I want to turn dovah.csv
into a dictionary for a translator.我想把dovah.csv
变成一个翻译字典。
Is there a way to specifically format it like this?有没有办法像这样专门格式化它?
english_to_dovahzul = {
'the': 'faal',
'quick': 'nel',
'brown': 'prun',
'fox': 'ilit'
}
dovahzul_to_english = {v: k for k, v in.english_to_dovahzul.items()}
You can try any example from below two:您可以尝试以下两个示例中的任何示例:
example 1: with file handling:示例 1:使用文件处理:
with open(filename) as stream:
result={}
for item in stream.readlines()[1:]:
line = item.strip().split()
result.update({line[0]:line[2]}) #line[i] is column index to create dict
print(result)
example 2: with pandas.示例 2:使用熊猫。
import pandas as pd
df = pd.read_csv(filename, sep='\t', lineterminator='\r')
result = dict(zip(df["English Word"],df["Dragon Translation"])) #df['column_name'] is column name to create dict
print(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.