2017-10-14 76 views
-2

所以我一直在学习Python几个月,并想知道如何去编写一个程序来计算一个单词在一个句子中出现的次数并打印出索引。如何计算单词在句子中出现的次数并打印出索引? (Python)

谢谢。

+1

嗨!欢迎SO。你已经使用Python好几个月了,但是你在创建一个问题之前是否试图“谷歌”这个?如果你没有先尝试某些东西(最好是带有链接),那么Ppl并不总是乐于帮助 –

+0

我建议你尝试一下,当你遇到一个特定问题时,回过头来写一个关于它的具体问题。 – khelwood

+0

谢谢,是的,我尝试在Google上搜索并找到一个Python程序,它可以计算一个单词在一个句子中出现的次数,但它不会打印出索引。 – Robbie

回答

-2

问题和我的答案改变了。这里是最后的建议:

string = "wordetcetcetcetcetcetcetcword" 

import re 
find = "word" 
p = re.compile(find) 
matches = [m.start() for m in p.finditer(string)] 
print(matches) 

返回:

[0, 25] 
+1

尽管如此,但它提供了其他地方可用的通用建议(人们不会阅读)。这与问题 – roganjosh

+0

@roganjosh我完全不同意。原来的问题是:请提供一步一步指导如何解决这个问题。 –

+1

您在某些代码中编辑了答案。我投票结束。澄清或downvote评论和继续。当您使用本网站工作时,您认为“Google this”对后代有帮助吗? – roganjosh

0

有几种方法可以做到这一点,但这里是一个计数的单词的实例数一个平凡的解决方案,但不采取例如punctation考虑:

from collections import Counter 
s = "This is true. This is false." 
c = Counter(s.split(' ')) 
print(c['This']) # Prints "2" 
0
def count_index(string, search_term): 
    return (search_term, 
     string.count(search_term), 
     [string.replace(search_term, '', i).index(search_term) + (len(search_term)*i) for i in range(string.count(search_term))] 
    ) 

返回

>>> a = test.count_index("python is a very good language, i like python because python is good", "python") 
>>> a 
('python', 3, [0, 39, 54]) 

的逻辑是(虽然有点bodgy)基本上会在一定范围内的search_term给定string从而索引的出现次数的单词,将索引添加到列表中;那么它将该词替换为无,然后在下一个词中增加根据当前索引删除的字符数量,并且循环工作得很好。

0

我们也欢迎学习者。以下可能会让你去;其包括基本治疗标点符号,以及返回的情况下,变化的相应索引处:

import string 
# 
mask = str.maketrans('', '', string.punctuation) # Punctuation mask. 
# 
def aFunc(sentence, word): 
    words = sentence.translate(mask).split(' ') # Remove punctuation. 
    indices = [(e,w) for (e,w) in enumerate(words) if w.lower() == word.lower()] # Collect (index,word) pairs. 
    return (len(indices), indices) 

s = 'The cat fell out of the hat. Then thE cAt fell asleep against the haT=:)' 

aFunc(s, 'HAT') 
(2, [(6, 'hat'), (14, 'haT')]) 

aFunc(s, 'the') 
(4, [(0, 'The'), (5, 'the'), (8, 'thE'), (13, 'the')]) 

aFunc(s, 'Cat') 
(2, [(1, 'cat'), (9, 'cAt')]) 
相关问题