【问题标题】:How can I find if a word (string) occurs more than once in an input/list in python如何查找一个单词(字符串)是否在 python 的输入/列表中多次出现
【发布时间】:2020-04-01 18:07:21
【问题描述】:

例如,如果示例输入是: 不要问你的国家能为你做什么 问问你能为你的国家做什么

我的程序必须返回: “国家”一词出现在第 5 位和第 17 位。

我只需要帮助查找字符串是否出现多次。

这是我目前的尝试,我是 python 新手,如果我的问题似乎太容易回答,我很抱歉。

# wordsList=[]
words=input("Enter a sentence without punctuation:\n")
# wordsList.append(words)
# print(wordsList)
for i in words:
    if i in words>1:
        print(words)
# words.split("  ")
# print(words[0])

【问题讨论】:

  • 请包含您编写的未产生正确输出的代码
  • 很抱歉给您带来不便,我编辑了我的帖子,不幸的是我的程序甚至出现了错误。
  • 看看这个老问题:stackoverflow.com/questions/4664850/…
  • 如果单词在字符串中出现 10,000 次会怎样?是不是应该说“XYZ这个词出现在第1、2、3、4、5、6......”?

标签: python


【解决方案1】:

查找出现次数

可能有几种方法可以做到这一点。一种简单的方法是将您的句子拆分为一个列表并找到出现的次数。

sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY" 
words_in_a_list = sentence.split(" ")
words_in_a_list.count("COUNTRY")

你也可以使用正则表达式,而且很容易做到。

import re

m = re.findall("COUNTRY", sentence)

查找每次出现的位置

您可能想阅读this post。 您可以使用search,它也返回跨度。并编写一个循环来找到它们。一旦你知道了第一个的位置,就开始从这么多字符中进一步搜索字符串。

def count_num_occurences(word, sentence):
    start = 0
    pattern = re.compile(word)
    start_locations = []
    while True:
        match_object = there.search(sentence, start)

        if match_object is not None:
            start_locations.append(match_object.start())
            start = 1 + match_object.start()
        else:
            break
    return start_locations

【讨论】:

  • 这如何产生单词所在位置的期望输出?
【解决方案2】:
str = 'ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY'

# split your sentence and make it a set to get the unique parts
# then make it a list so you ca iterate
parts = list(set(str.split(' ')))

# you count to get the nr of occurences of parts in the str
for part in parts:
    print(f'{part} {str.count(part)}x')

结果

COUNTRY 2x
YOU 4x
ASK 2x
YOUR 2x
CAN 2x
NOT 1x
DO 2x
WHAT 2x
FOR 2x

或有位置

import re

str = 'ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR DO YOUR COUNTRY'

# split your sentence and make it a set to get the unique parts
# then make it a list so you ca iterate
parts = list(set(str.split(' ')))

# you count to get the nr of occurences of parts in the str
for part in parts:
    test = re.findall(part, str)
    print(f'{part} {str.count(part)}x')
    for m in re.finditer(part, str):
        print('     found at', m.start())

结果

DO 3x
     found at 30
     found at 58
     found at 65
ASK 2x
     found at 0
     found at 41
COUNTRY 2x
     found at 18
     found at 73
YOUR 2x
     found at 13
     found at 68
WHAT 2x
     found at 8
     found at 45
YOU 4x
     found at 13
     found at 37
     found at 50
     found at 68
NOT 1x
     found at 4
FOR 2x
     found at 33
     found at 61
CAN 2x
     found at 26
     found at 54

【讨论】:

  • 感谢您的帮助。请问最后一行 f' 是做什么的。它会调用函数吗?
  • 错字,对不起,我会删除它。 f' { ]' 用于格式化带有变量的文本。参见 f'{part} {str.count(part)}x'。它使用 {} 中的 2 个变量的值创建一个字符串。
【解决方案3】:

如果您只想要多次出现的单词:

words=input("Enter a sentence without punctuation:\n").strip().split()
word_counts = {}

for word in words:
    if word in word_counts:
        word_counts[word] += 1
    else:
        word_counts[word] = 1

for word in word_counts.keys():
    if word_counts[word] > 1:
        print(word)

只需将所有计数存储在字典中,然后循环遍历字典以打印多次出现的计数。

同样高效,因为它只通过输入一次,然后再通过字典一次

如果你想要单词的实际位置:

words=input("Enter a sentence without punctuation:\n").strip().split()
word_counts = {}

for i in len(words):
    word = words[i]
    if word in word_counts:
        word_counts[word].append(i) // keep a list of indices
    else:
        word_counts[word] = [i]

for word in word_counts.keys():
    if len(word_counts[word]) > 1:
        print("{0} found in positions: {1}".format(word, word_counts[word]))

【讨论】:

  • 请问 word_counts 作为字典而不是列表有多重要,以及它有什么帮助。我是python的初学者。提前谢谢你。
  • 因此,通过将单词计数作为字典,您可以存储单词及其计数。所以第一个循环会产生类似{"ASK": 2, "NOT": 1, "WHAT": 2, ...}的东西然后第二个循环打印出相应计数大于1的单词。如果你使用一个列表,你必须循环遍历每个单词的列表以获得它的计数,然后打印它。这是 O(n^2) 的字典,你只能遍历单词两次
猜你喜欢
  • 2017-12-17
  • 2017-06-03
  • 1970-01-01
  • 1970-01-01
  • 2022-11-27
  • 2018-12-17
  • 1970-01-01
  • 1970-01-01
  • 2023-01-22
相关资源
最近更新 更多