我想改革这个
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 ( ) ):
答案 0 :(得分:3)
您可以使用以下内容:
private void btn_start_Click(object sender, EventArgs e)
{
//new added code
if (btn_start.Text == "Start")
{
btn_start.Text = "Pause";
sorting = true;
sort();
}
else if (btn_start.Text == "Pause")
{
btn_start.Text = "Continue"; // '= "Start"' in the old code
tmr_sorting.Stop();
sorting = false;
}
// new added code
else if (btn_start.Text == "Continue")
{
btn_start.Text = "Pause";
sorting = true;
}
}
在上面enumerate
将从输入文件返回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)
开始。然后,对于每一行,strip
用于删除尾随换行符,然后每行1
的行为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(','))
答案 1 :(得分:2)
将此文件包含在文件的顶部,以便您可以使用print
函数(Python 3中不推荐使用print
语句。)
from __future__ import print_function
然后你应该根据,
:
for word in line.split(','):
print(word, n+1, file=w)
答案 2 :(得分:1)
这是一个小例子,展示了如何处理在Python中拆分字符串(请注意,这是用Python 3编写的,所以你必须为Python 2.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))