python - 如何将字符串彼此放在一起并为其分配一个数字?

标签 python python-2.7

我要改造这个

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 ( ) ):

最佳答案

您可以使用以下内容:

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(',')))

在上面enumerate将从输入文件返回 (index, line) 元组,索引从作为参数传递的 1 开始。然后对于每一行 strip用于删除尾随换行符,然后行是 split来自每个 ,。最后,生成器表达式输出格式为 '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

关于python - 如何将字符串彼此放在一起并为其分配一个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41297652/

相关文章:

python - 正则表达式仅匹配文本中的坐标元组

python - __test__ = False 魔法属性如何用于测试发现

python - 在导入模块 __init.py__ 之前设置变量

Python 元类与对象实例化一起使用

python - 将省略号放在seaborn catplot上

python - 为什么我的 python mechanize 脚本无法用于该特定站点

python - Multiindex 中的 Pandas 自定义排序行

python - 为什么 'the' 在 .remove 之后仍然存在?

python - 保龄球调度程序

python - 比较不同类型时如何强制 Python 2 引发异常?