如何把字符串放在一起并给它赋值?

2024-06-28 19:41:32 发布

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

我想改变这一切

A,B                   
AFD,DNGS,SGDH         
NHYG,QHD,lkd,uyete    
AFD,TTT

并为每一行指定一个数字,即

A 1
B 1
AFD 2
DNGS 2
SGDH 2
NHYG 3
QHD 3
lkd 3
uyete 3   
AFD 4
TTT 4

我怎样才能做到这一点?你知道吗

我被困在以下代码中:

import itertools
# open the data from the directory
with open ( './test.txt' ) as f:
    # Make a file named result to write your results there
    with open ( 'result.txt' , 'w' ) as w:
        # read each line with enumerate ( a number for each string)
        for n , line in enumerate ( f.readlines ( ) ):

Tags: thetxtaswithresultopeneachttt
3条回答

您可以使用以下选项:

with open('test.txt') as f_in, open('result.txt', 'w') as f_out:
    f_out.write('\n'.join('{} {}'.format(s, i)
                          for i, l in enumerate(f_in, 1)
                          for s in l.strip().split(',')))

在上面^{}将从输入文件返回(index, line)元组,索引从作为参数传递的1开始。然后,对于每一行,使用^{}删除尾随换行符,然后从每一行,删除一行^{}。最后,生成器表达式输出格式为'word index'的字符串,这些字符串在写入输出文件之前用换行符连接在一起。你知道吗

更新如果要打印结果而不是写入文件,可以使用以下代码:

with open('test.txt') as f_in:
    print '\n'.join('{} {}'.format(s, i)
                    for i, l in enumerate(f_in, 1)
                    for s in l.strip().split(','))

输出:

A 1
B 1
AFD 2
DNGS 2
SGDH 2
NHYG 3
QHD 3
lkd 3
uyete 3
AFD 4
TTT 4

在文件的顶部包含这个函数,这样就可以使用print函数(在python3中,print语句是不推荐的)。你知道吗

from __future__ import print_function

然后您应该基于,分割行:

        for word in line.split(','):
            print(word, n+1, file=w)

下面是一个演示如何在Python中处理字符串拆分的小示例(请注意,这是用Python3编写的,因此您必须将其改编为Python2.7):

arr = ("A,B","AFD,DNGS,SGDH","NHYG,QHD,lkd,uyete","AFD,TTT")
for i in range(0,len(arr)):
    splitarr = arr[i].split(",")
    for splitItem in splitarr:
        print(splitItem + " " + str(i+1))

相关问题 更多 >