我正在编写一个程序,其中显示起始句子并且用户必须输入句子中的单词,以便程序可以告诉用户单词在句子中的位置。我希望程序接受每个案例,但目前它只接受UPPER案例。有人可以帮助我如何使它不区分大小写,并在用户输入时仍然告诉用户这些单词的位置?谢谢:))
到目前为止,这是我的代码:
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,"!")
答案 0 :(得分:1)
==
运算符检查等效性,它不会分配任何内容。这行代码:sentence == sentence.lower()
应为sentence = sentence.lower()
,其下的行应为word = word.lower()
。
此外,由于您在程序的最开始时将sentence
拆分为sentence2
,sentence.lower()
不会更改sentence2
,这意味着它永远无法获得单词因为sentence2
全部为大写,word
全部为小写。要解决此问题,请删除sentence2
并将此最后一个for语句替换为类似
for (num, x) in enumerate(sentence.split()):
答案 1 :(得分:0)
使用word
将word = word.lower()
转换为大写,并删除以下行:
sentence == sentence.lower()
word == word.lower()
答案 2 :(得分:0)
这是我能想到的最直接的方式
>>> 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]
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]}
现在你有一本字典,你需要处理不存在的单词。因为这使用了defaultdict,所以您可以获得额外的好处,即对缺失索引的直接查找将返回一个空列表。
>>> print(position_index["they".upper()])
[]
所以你可以简单地
>>> 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
答案 3 :(得分:0)
var filter = new HttpBaseProtocolFilter();
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
var httpClient = new Windows.Web.Http.HttpClient(filter);
目前这不适用于以标点符号结尾的内容(忘了,做)。这是因为我们直接评估了这两个。我看到的唯一方法是执行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)
运算符。这当然会让位于更大的问题,(输入:输出:询问,什么,可以。这是因为' a'在技术上都是三个!)!希望这可以帮助!这也只返回单词的第一个索引。这可以通过列出职位列表来修改。在循环结束时in
我们len(list) > 0
,绕过第二次打印。它取决于你!