简体   繁体   English

当我在程序中输入单词时,如何使程序接受任何情况

[英]How do I get my program to accept any case when I enter a word into it

I am writing a program where a starting sentence is displayed and the user has to input a word that is in the sentence, so that the program can tell the user the position the word is in the sentence. 我正在编写一个程序,其中显示了一个起始句子,用户必须输入句子中的单词,这样程序才能告诉用户该单词在句子中的位置。 I want the program to accept every case but at the moment it only accepts UPPER case. 我希望程序接受所有情况,但目前仅接受大写。 Can someone please help me on how to make it case insensitive and still tell the user the positions of the words when they input them? 有人可以帮助我使它不区分大小写,并且在输入单词时仍然告诉用户单词的位置吗? Thanks :) 谢谢 :)

Here is my code so far: 到目前为止,这是我的代码:

import time

sentence = ("ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY")

sentence2 = sentence.split()

print(sentence)

time.sleep(1)

word = input("Enter Word: ")

print(word)

sentence == sentence.lower()

word == word.lower()

if word in sentence:

    print("Word is valid")

elif word not in sentence:

    print("Word is invalid")


for (num, x) in enumerate(sentence2):

    if word == x:

       print ("Your word is in position ",num+1,"!")

The == operator checks for equivalency, it doesn't assign anything. ==运算符检查是否相等,它不分配任何内容。 This line of code: sentence == sentence.lower() should be sentence = sentence.lower() and the line under that should be word = word.lower() . 这行代码: sentence == sentence.lower() word = word.lower()应该是sentence = sentence.lower() word = word.lower()下面的那一行应该是word = word.lower()

In addition, since you split sentence into sentence2 at the very beginning of the program, sentence.lower() does not change sentence2 , meaning it will never get the position of the word because sentence2 is all uppercase and word is all lowercase. 此外,由于你拆分sentencesentence2在节目的一开始, sentence.lower()不改变sentence2 ,这意味着它永远不会得到了这个词的位置,因为sentence2是全是大写的word是全部小写。 To fix this, get rid of sentence2 and replace your last for statement with something like this 要解决此问题,请摆脱sentence2并使用类似以下内容替换您的最后一个for语句

for (num, x) in enumerate(sentence.split()):

Convert word to uppercase with word = word.lower() and remove the following lines: 使用word = word.lower()word转换为大写并删除以下几行:

sentence == sentence.lower()
word == word.lower()

This is the most straightforward way I can think of 这是我想到的最简单的方法

>>> import collections
>>> position_index = collections.defaultdict(list)
>>> sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"
>>> for index, word in enumerate(sentence.split()):
...     position_index[word].append(index)
...
>>> position_index["can".upper()]
[5, 12]
>>> position_index["what".upper()]
[2, 10]

The for loop builds a dictionary-like data structure that looks like this for循环建立一个类似于字典的数据结构,如下所示

{'DO': [6, 13], 'WHAT': [2, 10], 'FOR': [7, 14], 'COUNTRY': [4, 16], 'ASK': [0, 9], 'CAN': [5, 12], 'NOT': [1], 'YOU': [8, 11], 'YOUR': [3, 15]}

Now that you have a dictionary you need to handle words that are not present as well. 现在您已经有了字典,您还需要处理不存在的单词。 Because this uses a defaultdict you get the added benefit that direct lookups on missing indexes will return an empty list. 因为这使用了defaultdict,所以您获得了额外的好处,即对丢失的索引进行直接查找将返回一个空列表。

>>> print(position_index["they".upper()])
[]

So you can simply 所以你可以简单地

>>> word = "what"
>>> positions = position_index[word.upper()]
>>> if positions:
...     print("The word '%s' appears at position(s): %s" %(word, ",".join(map(str, positions)),))
... else:
...     print("The word '%s' does not appear" %(word,))
...
The word 'what' appears at position(s): 2, 10
def findPos(sentence, word):
sentence = sentence.lower().split(' ')
word = word.lower()
index = 0
for i in sentence:
    if word == i:
        print '%s is a valid word and is found at position %s'%(word, index)
        return
    index += 1
    print i
print '%s is not a valid word'%word

sentence = 'Ask not what you can do... I forgot!!'
word = raw_input('What is your word?: ')
findPos(sentence, word)

Currently this will not work for things that end in punctuation (forgot, do). 目前,这不适用于以标点符号结尾的事情(忘记做)。 This is because we directly evaluate the two. 这是因为我们直接评估两者。 The only way I see around that is to do the in operator. 我看到的唯一方法是执行in运算符。 This of course will give way to even larger issues, (Input:a Output:Ask, what, can. This is because 'a' is technically in all three!)! 当然,这将让位于更大的问题(输入:a输出:问,可以)。这是因为从技术上讲,“ a”在所有三个方面都存在!)! Hope this helps! 希望这可以帮助! This also only returns the first index of the word. 这也仅返回单词的第一个索引。 This could be modified by having a list of positions. 可以通过列出职位来进行修改。 At the end of the loop if len(list) > 0 we return , bypassing the second print. 如果len(list) > 0 ,则在循环结束时return ,绕过第二次打印。 It's up to you! 由你决定!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在列表中接受0作为值? 当我在空格后输入数字时,我收到错误 - How to accept 0 as a value in a list? and When I enter the numbers after a space I get an error 为什么我在运行程序时输入的前两个输入会在文本文件中重复? - Why do the first two inputs I enter when I run my program repeat in the text file? 当我的程序没有告诉我任何错误时如何修复我的程序 - How do I fix my program when it doesn't tell me any errors 如果我在程序中输入5却没有其他字母或数字,为什么我的程序将s和c错位? - Why is my program shifting s and c by the wrong amount if I enter 5 into my program but not with any other letters or number? 我怎样才能让我的程序拒绝字母输入,只接受数字输入? - How can i get my program to reject letter inputs, and only accept number inputs? 我怎么得到这个词? - How do I get the word? 我如何制作这个程序,以便当用户输入用户名时它不接受系统中已经存在的用户名[暂停] - how do i make this program so that when the user inputs a username it does not accept a username that is already in the system [on hold] {Py3}我如何让用户按下一个键并继续执行程序而又不按Enter键? - {Py3} How do I get a user to press a key and carry on the program without pressing enter after? 我如何在python中的程序和箭头键,退格键,回车键等之外获取击键? - how do i get keystrokes outside of program and of arrow keys, backspace, enter, etc in python? 从程序将代码写入文件时,如何让我的字典开始一个新行? - How do I get my dictionary to begin a new line when writing code to a file from a program?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM