当值对和lis满足条件时创建新列表

2024-05-18 23:33:21 发布

您现在位置:Python中文网/ 问答频道 /正文

这是第一个问题。我已经试着找到一个解决办法大约一个星期了,但我终于不得不问了。我对这个问题的题目也持开放态度。你知道吗

我在用Python3

我有一个csv文件(图例.csv)包含两个标题(键),一个用于数字,一个用于缩写。你知道吗

每个abbr都有一个对应的编号,这在csv文件中表示。你知道吗

我还有一份名单(列表.txt),名字的第一部分通常是某种缩写。你知道吗

这个程序背后的想法是:我想分析csv文件,并在文件名中添加与缩写相对应的数字列表.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的好资源的话。你知道吗


Tags: 文件ofcsvintxtforexample数字
1条回答
网友
1楼 · 发布于 2024-05-18 23:33:21

你可以试试这个:

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文件的头之后开始,这对我们解决问题没有帮助。从这里,算法尝试确定缩写是否包含在行的第一部分,在本例中存储为i。如果是这样,数字和行将以所需输出的样式打印。你知道吗

相关问题 更多 >

    热门问题