Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python如何计算每个单词在句子中出现的次数?_Python_String_Word Count - Fatal编程技术网

Python如何计算每个单词在句子中出现的次数?

Python如何计算每个单词在句子中出现的次数?,python,string,word-count,Python,String,Word Count,嘿,伙计们,我很困惑,很不确定为什么我的代码不起作用。我在这段代码中所做的是试图从我拥有的句子的列表中找到某些单词,并输出在句子中重复的次数 vocabulary =["in","on","to","www"] numwords = [0,0,0,0] mysentence = (" ʺAlso the sea tosses itself and breaks itself, and should any  sleeper fancying that he might find on the b

嘿,伙计们,我很困惑,很不确定为什么我的代码不起作用。我在这段代码中所做的是试图从我拥有的句子的列表中找到某些单词,并输出在句子中重复的次数

vocabulary =["in","on","to","www"]
numwords = [0,0,0,0]
mysentence = (" ʺAlso the sea tosses itself and breaks itself, and should any  sleeper fancying that he might find on the beach an answer to his doubts, a  sharer of his solitude, throw off his bedclothes and go down by himself to  walk on the sand, no image with semblance of serving and divine  promptitude comes readily to hand bringing the night to order and making  the world reflect the compass of the soul.ʺ)
for word in mysentence.split():
              if (word == vocabulary):
                  else:
                  numwords[0] += 1
              if(word == vocabulary):
                  else:
                  numwords[1] +=1
              if (word == vocabulary):
                  else:
                  numwords [2] += 1
              if (word == vocabulary):
                  else :
                  numwords [3] += 1
              if (word == vocabulary):
                  else:
                  numwords [4] += 1


print "total number of words : " + str(len(mysentence))

最简单的方法是使用
集合。Counter
计算句子中的所有单词,然后查找您感兴趣的单词

from collections import Counter
vocabulary =["in","on","to","www"]
mysentence = "Also the sea tosses itself and breaks itself, and should any  sleeper fancying that he might find on the beach an answer to his doubts, a  sharer of his solitude, throw off his bedclothes and go down by himself to  walk on the sand, no image with semblance of serving and divine  promptitude comes readily to hand bringing the night to order and making  the world reflect the compass of the soul."
mysentence = mysentence.split()
c = Counter(mysentence)
numwords = [c[i] for i in vocabulary]
print(numwords)

考虑这样一个问题,像“and”这样的字符可能无法很好地解析,除非指定了适当的编码方案

this_is_how_you_define_a_string = "The string goes here"

# and thus:

mysentence = "Also the sea tosses itself and breaks itself, and should any  sleeper fancying that he might find on the beach an answer to his doubts, a  sharer of his solitude, throw off his bedclothes and go down by himself to  walk on the sand, no image with semblance of serving and divine  promptitude comes readily to hand bringing the night to order and making  the world reflect the compass of the soul."

for v in vocabulary:
    v in mysentence # Notice the indentation of 4 spaces

如果v i在mycentence中,此解决方案将返回
TRUE
FALSE
。我想我会离开作为一个练习如何积累的价值。提示:TRUE==1,FALSE=0。您需要每个单词的真值之和
v

大概您可以使用for循环遍历列表,检查它是否在列表中,然后递增计数器-示例实现可能如下所示

def find_word(word,string):
    word_count = 0
    for i in range(len(string)):
        if list[i] == word:
            word_count +=1

这可能有点低效,但我相信这对您来说可能比收集更容易理解。计数器:)

我会这样做,诚实地检查:

for word in mysentence.split():
    if word in vocabulary:
        numwords[vocabulary.index(word)] += 1
因此,您的整个代码如下所示:

vocabulary = ["in", "on", "to", "www"]
numwords = [0, 0, 0, 0]
mysentence = (" ʺAlso the sea tosses itself and breaks itself, and should any  sleeper fancying that he might find on the beach an answer to his doubts, a  sharer of his solitude, throw off his bedclothes and go down by himself to  walk on the sand, no image with semblance of serving and divine  promptitude comes readily to hand bringing the night to order and making  the world reflect the compass of the soul.ʺ")
for word in mysentence.replace('.', '').replace(',', '').split():
    if word in vocabulary:
        numwords[vocabulary.index(word)] += 1

print("total number of words : " + str(len(mysentence)))

正如@Jacob所建议的,在拆分之前也可以替换“.”和“,”字符,以避免任何可能的冲突。

请更新问题中的代码。您给出的代码示例的预期输出是什么?此处显示的代码与您机器上显示的代码相同吗?请查看。这里的例子将有助于使用。告诉我们您尝试了什么。阅读更多关于如何提问的内容,如果你想获得分数之类的。这是一种类似于蟒蛇的提问方式。对于初学者来说可能有点高级,但概括得很好。这个列表很优雅!这应该是某种发电机吗?您缺少
yield
和某种
def
语句