这里的第一个问题。我已经尝试找到解决方案大约一个星期了,但我终于不得不问了。我也愿意接受有关此问题标题的建议。
我正在使用 python3
我有一个 csv 文件 (legend.csv),其中包含 2 个标题(键),一个用于数字,一个用于缩写。
每个缩略语都有一个对应的数字,这在 csv 文件中表示。
我还有一个名字列表(list.txt),名字的第一部分通常是某种缩写。
程序背后的想法是:我想分析 csv 文件并添加与 list.txt 中名称中的缩写相对应的数字。如果可能,输出应该是一个新的文本文件。
example of list.txt:
addg-stuff
cbdd-stuff
abc-stuff
add-stuff
example of legend.csv:
number,abbr
0001,addg
0002,cbdd
0003,abc
0004,add
example of desired output:
0003-abc-stuff
0001-addg-stuff
0004-add-stuff
0002-cbdd-stuff
下面找到了缩写,但我一直在研究如何将相应的数字添加到名称中。 Easiest way to cross-reference a CSV file with a text file for common strings
上面的链接是我找到如何提取匹配字符串的地方,但不确定从这里去哪里。
import csv
with open("legend.csv") as csvfile:
reader = csv.reader(csvfile)
searchstring = {row[1] for row in reader}
num = {row[0] for row in reader}
with open("list.txt") as txtfile:
for names in txtfile:
for i in searchstrings:
if i in name:
matching = (name) #not sure where to go from here. If matching is printed, the names are found that contain the abbr.
绝对是新手,刚开始接触 python 一个月左右。 任何帮助将不胜感激,特别是如果您对这种情况或一般情况下的 python 有任何好的资源。
最佳答案
你可以试试这个:
import csv
f1 = open('legend.csv')
f1 = csv.reader(f1) #splitting at instances of commas
f1 = list(f1)
f2 = open('list.txt').read().splitlines() #reading every line in the txt file
for i in f2:
for b in f1[1:]:
if i.split("-")[0] == b[1]:
print str(b[0])+"-"+i
输出:
0001-addg-stuff
0002-cbdd-stuff
0003-abc-stuff
0004-add-stuff
在双 for 循环中,算法从 txt 文件中获取一行,然后从 csv 文件中获取一行。请注意,f1[1:]
是列表切片。也就是说我们是在csv文件的header之后开始的,这对我们解决问题没有帮助。从那里,算法尝试确定缩写是否包含在该行的第一部分中,在本例中存储为 i
。如果是这样,数字和行将以所需输出的样式打印。
关于python - 当一个条件满足一个值对和一个列表时创建一个新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44913522/