|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 allenyang 于 2017-1-13 11:16 编辑
纯菜鸟学了几个星期的python
查了好几天的资料
写了个四不像的东西
大家帮忙看看怎么改进达到目的
import collections
from collections import Counter
lines = open('ID1.txt','r').readlines()
out = open('ID2.txt','w')
counts = Counter(lines)
for s,num in counts.items():
if num > 1:
for suffix in range(1, num + 1):
lines[lines.index(s)] = s + '-' + str(suffix)
out.write(str(lines))
print(lines)
我的目标是把 'ID1.TXT' 文档中重复的数据重新命名然后输出到 ‘ID2.TXT’,如下
001
001
002
002
输出为:
001-1
001-2
002-1
002-2
但是这个给我的输出是
['001\n-1', '001\n-2', '002\n-1', '002\n-2']
lines[lines.index(s)]这里应该就不对了,但是实在不知道怎么改了
求大牛们指教一下,不胜感激
- import collections
- from collections import Counter
- L = open('ID1.txt','r').readlines()
- lines = []
- for x in L:
- lines.append(x.strip())
- #out = open('ID2.txt','a')
- counts = Counter(lines)
- for s,num in counts.items():
- if num > 1:
- for suffix in range(1, num + 1):
- lines[lines.index(s)] = s + '-' + str(suffix)
- #out.write(str(lines))
- print(lines)
- for y in lines:
- with open('ID2.txt','a') as f:
- f.write(y+'\n')
-
复制代码
看看我帮你改的,仔细比对我改动的地方,你看懂了我改的就知道出错在哪里了
|
|