2016-11-17 52 views
-2

我試圖將一個句子打斷爲諸如「這個男孩很好」的句子,然後在每個字母的句子中獲得這個位置,但是每次我都會寫'o ',這兩個字母的地方保持不變。我怎樣才能分開這兩個相同的字母?帶重複字符的字符串數組python

with open("d:\Users\hazembazem\Desktop\python random\crap\encrypt.txt", "rb") as f: 
    file= f.read() 
    print file 
    file= list(file) 
    for item in file: 
     a=file.index(item) 
    print (a) 

該文件只是一個txt文件,其中包含「該男孩很好」。

一個,就是要字符的地方,但它不是我顯示了這個:

0 
1 
2 
3 
4 
5 
6 
3 
8 
9 
10 
3 
12 
5 
5 
15 
+0

你能後你有這麼遠的代碼? – duncan

+0

如果我們看不到它,我們該如何解決一些問題? – MooingRawr

+1

這是因爲'str.find(substring)'方法返回了子串的最左邊的索引。 - 只是爲了澄清,如果你仍然不知道爲什麼它會發生。 – Nf4r

回答

2

string.index(s, sub[, start[, end]])

find()但提高ValueError時沒有找到的子字符串。


string.find(s, sub[, start[, end]])

返回最低指數s,其中子sub發現...


所以,是的,那是不是你想。

檢查了這一點

with open("filename") as f: 
    string = f.read() 
    print range(len(string)) 
    for i,c in enumerate(string): 
     print i,c 

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] 
0 t 
1 h 
2 e 
3 
4 b 
5 o 
6 y 
7 
8 w 
9 a 
10 s 
11 
12 g 
13 o 
14 o 
15 d 
0

str.index/str.find只返回最左邊的指數。在找到每個字母后,您需要通過要開始搜索字母的索引。事情是這樣的:

>>> found = -1 
>>> for i in xrange(x.count('o')): 
>>>  found = x.index('o', found+1) 
>>>  print 'Found "o" at index: {}'.format(found) 

Found "o" at index: 5 
Found "o" at index: 13 
Found "o" at index: 14 
0

如果您遍歷使用索引for循環的文字,你可以簡單地使用索引同時打印的字符,它的位置

text = list(file) 
for index in range(0,len(text)): 
    print(a[index], index) 
0

如果您想要在字符及其相應索引之間進行映射並以的形式進行存儲,您可以使用沿着collections.defaultdict()enumerate()爲:

from collections import defaultdict 

my_string = "the boy was good" 
char_mapping = defaultdict(list) 

for i, c in enumerate(my_string): 
    char_mapping[c].append(i) 

# Content of `char_mapping`: 
# {'a': [9], 
# ' ': [3, 7, 11], 
# 'b': [4], 
# 'e': [2], 
# 'd': [15], 
# 'g': [12], 
# 'h': [1], 
# 'o': [5, 13, 14], 
# 's': [10], 
# 't': [0], 
# 'w': [8], 
# 'y': [6]})