Python 如何获取列表中的名称数,然后将结果写入文件?

Python 如何获取列表中的名称数,然后将结果写入文件?,python,Python,我是python新手,在这个(很可能很简单)问题上遇到了困难。我正在接受一个格式为的文件 name_of_sports_team year_they_won_championship e、 g 它们已被分隔为嵌套列表[年份][名称]。我的任务是将列表中的所有重复项相加,并将它们显示在一个新文件中 Toronto 2 Minnesota 1 我的代码如下- def write_tab_seperated(n): ''' N is the filename

我是python新手,在这个(很可能很简单)问题上遇到了困难。我正在接受一个格式为的文件

name_of_sports_team    year_they_won_championship
e、 g

它们已被分隔为嵌套列表[年份][名称]。我的任务是将列表中的所有重复项相加,并将它们显示在一个新文件中

Toronto    2 
Minnesota    1
我的代码如下-

def write_tab_seperated(n):
    '''
    N is the filename
    '''

    file = open(n, "w")

    # names are always in the second position?
    data[2] = names

    countnames = () 
    # counting the names 
    for x in names:
    # make sure they are all the same    
    x = str(name).lower()
        # add one if it shows. 
        if x in countnames:
            countnames[x] += 1
        else:
            countnames[x] = 1
    # finish writing the file 
    file.close
这是非常错误的,很有趣,但我已经计划好了今后的方向:

  • 拿着文件
  • 在名单上分开
  • 每次重复加1
  • 以名称(选项卡)编号格式显示
  • 关闭文件

感谢您的帮助,并提前向您表示感谢

python的一大优点是有大量的包。对于处理表格数据,我建议使用和格式:


尽管如此,我仍然强烈建议您仔细阅读您的代码,并从零开始了解这些事情是如何完成的。

根据我对您的解释的理解,以下是我的代码:

#input.txt is the input file with <year><tab><city> data
with open('input.txt','r') as f:
    input_list =[x.strip().split('\t') for x in f]

output_dict = {}
for per_item in input_list:
    if per_item[1] in output_dict:
        output_dict[per_item[1]] += 1
    else:
        output_dict[per_item[1]] = 1

#output file has <city><tab><number of occurence>
file_output = open("output.txt","w")
for per_val in output_dict:
    file_output.write(per_val + "\t" + str(output_dict[per_val]) + "\n")
#input.txt是包含数据的输入文件
将open('input.txt','r')作为f:
input_list=[x.strip().split('\t'),用于f中的x]
输出_dict={}
对于输入列表中的每项:
如果输出指令中的每项[1]:
输出目录[每项[1]]+=1
其他:
输出目录[每项[1]]=1
#输出文件已被删除
文件输出=打开(“output.txt”、“w”)
对于输出指令中的每值:
文件\u output.write(per_val+“\t”+str(output\u dict[per_val])+“\n”)

如果有帮助,请告诉我

有一个内置的数据类型非常适合您的用例,名为

从示例I/O格式中,我假设数据文件列是以制表符分隔的。在问题文本中,它看起来像4个空格-如果是这样,只需将下面的
'\t'
更改为
'
'*4

with open('data.tsv') as f:
    lines = (l.strip().split('\t') for l in f.readlines())
一旦读入数据,就可以将其传递给计数器并指定它应该在第二列中的值上创建计数

from collections import Counter

c = Counter(x[1] for x in lines)
并将其打印出来以供参考:

for k, v in c.items():
    print('{}\t{}'.format(k, v))
输出:

Minnesota   1
Toronto 2

嘿@Speter,你想重新构造代码还是让它尽可能相似?@PeterDolan我没有偏好,看到这是一个很好的机会,我进入了一个错误的兔子洞。我添加了一个使用python计数器数据类型的示例,它在这里非常有用。我不确定这是否回答了这个问题-OP不想从磁盘读取数据并检查它吗?你是snippet将数据写入磁盘。他的函数名为
write\u tab\u separated()
,所以我很确定他想写。回答得很好。吹毛求疵,但是对于f.read()中的l.strip().split('\n')->
对于f.readlines()中的l.readlines()如何呢如果l
我对
readlines()
的一个警告是,它在每一行上都保留了尾随的
\n
,但是总体来说,这有点干净-我只是更新了它来使用它,并用生成器替换了列表理解。
for k, v in c.items():
    print('{}\t{}'.format(k, v))
Minnesota   1
Toronto 2