2016-11-17 115 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]})