Skip to content

Instantly share code, notes, and snippets.

@fkztw
Last active August 29, 2015 14:20
Show Gist options
  • Save fkztw/3366b9fc6934674c4ea6 to your computer and use it in GitHub Desktop.
Save fkztw/3366b9fc6934674c4ea6 to your computer and use it in GitHub Desktop.
作者  Dong0129 (阿東)                                              看板  Python
標題  [問題] 該怎麼用dict處理這個問題?(附上code@@)
時間  Mon Apr 27 21:19:14 2015
─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─

各位版友好,

請問我該如何運用dict轉換以下需求?

file1:
2>4
1>2
2>3
3>5
3>1
1>4
4>2
.
.
.
轉換成:
file2:
1.1>2.1
3.1>1.2
1.3>4.1
4.2>5.1
4.3>3.2
3.3>2.2
2.3>1.4
.
.
.

即.左邊的數字為第幾種,而.右邊的數字為出現幾次,

麻煩各位大大幫幫忙了!


目前撰寫的程式為:
rfd=open(file1,"r")
wfd.open(file2,"w")
dict_file=dict()
num={}
seq={}
for line in rfd.read().splitlines():
        item1,item2=line.split('>')
        for item in (item1,item2):
                if not item in num:
                        num[item]=1
                        seq[item]=len(num.keys())
                else:
                        num[item]+=1
                dict_file.setdefault(item,str(seq[item])+"."+str(num[item]))
        wfd.write(dict_file[item1]+'>'+dict_file[item2])
rfd.close()
wfd.close()
file2的內容:
1.1>2.1
3.1>1.1
1.1>4.1
.
.
.

好像在執行dict_file.setdefault那ㄧ句寫不進去...

請問我有哪裡寫錯嗎?
file1 = '1.txt'
file2 = '2.txt'
rfd = open(file1, "r")
wfd = open(file2, "w")
dict_file = {}
num = {}
seq = {}
for line in rfd.read().splitlines():
item1, item2 = line.split('>')
for item in (item1, item2):
if not item in num:
num[item] = 1
seq[item] = len(num.keys())
else:
num[item] += 1
dict_file[item] = str(seq[item]) + "." + str(num[item])
#dict_file.setdefault(item, str(seq[item]) + "." + str(num[item]))
wfd.write('{}>{}\n'.format(dict_file[item1], dict_file[item2]))
rfd.close()
wfd.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment