1

我有这个问题。我有两个文件.txt,match_list格式如下:

Sevilla, Ath Bilbao
Valencia, Valladolid
Getafe, Atl. Madrid 

data

Getafe, Atl. Madrid,5:00 PM, Coliseum Alfonso Pérez, 9.500,27.8, 2.760.000,8
Valencia, Real Valladolid,7:00 PM, Mestalla, 41.000,26.3, 8.640.000,6
Sevilla, Ath Bilbao,8:00 PM, Ramón Sánchez Pizjuan, 4-2-3-1,26, 5.488.000,11

我想遍历这两个文件,匹配团队名称并将与每个匹配项对应的所有数据从 复制data.txtmatch_list.txt.

我的代码无法处理这个问题(可能是因为我只循环一个文件?):

match_data = open('data.txt').readlines()
match_list = open('m_list.txt').readlines()
outfile = open('done.txt', 'w')

for line in match_data:
    if line[:2] == match_list[:2]:
        match_list = match_list+',' + line[2:]
        outfile.write(match_list)
4

4 回答 4

2

您有 CSV 数据,请使用csv模块读取它们。首先读data.txt入内存,读入以前两列为键的字典:

import csv

with open('data.txt', 'rb') as match_data:
    reader = csv.reader(match_data)
    match_data = {tuple(row[:2]): row for row in reader}

with open('m_list.txt', 'rb') as match_list, open('done.txt', 'wb') as outfile:
    reader = csv.reader(match_list)
    writer = csv.writer(outfile)

    for row in reader:
        row = tuple(row)
        if row in match_data:
            writer.writerow(match_data[row])
于 2013-04-12T16:33:43.447 回答
1

打扰一下。我在您的问题中看到了“批处理文件”标签,因此我发布了批处理文件 .bat 解决方案作为替代方案。我的方法包括首先将所有文件行data加载到由团队名称索引的数组中;这样,在处理文件时,可以直接访问match_list对应的元素。data这里是:

@echo off
setlocal EnableDelayedExpansion

rem Load all lines of data.txt file into data array indexed by team name
for /F "tokens=1* delims=," %%a in (data.txt) do (
   set data[%%a]=%%b
)

rem Process lines of m_list.txt file and output the corresponding data into done.txt file
(for /F "delims=," %%a in (m_list.txt) do (
   echo %%a, !data[%%a]!
)) > done.txt
于 2013-04-13T00:57:32.137 回答
1

尝试这个:

for line in match_list:
    for x in match_data:
        if x.startswith(line.split(',')[0]):
            outfile.write(line +', '+ x)
            break

我没有对每个字符串进行任何格式化,如果你愿意,你可以这样做。但是因为可能两个文件中的顺序不同,您要么需要执行匹配(如果您将它们读入真实的数据结构会更容易 -csv如果您愿意,可以尝试),或者只是循环两个假设它们不是太大的列表。

于 2013-04-12T16:28:13.493 回答
1

您的 data.txt 不是您希望 match_list.txt 采用的格式吗?

for line in match_data :
   for match in match_list :
      if match[:-1] in line : # careful of \n
         # write line to file
         break
于 2013-04-12T16:36:29.467 回答