【问题标题】:How to strip capital letters and then put them back in again in the same place?如何剥离大写字母,然后将它们重新放回同一个地方?
【发布时间】:2016-09-22 02:40:13
【问题描述】:

我需要输入一个大小写混合的句子,并输出每个单词的位置。但是,如果一个单词是大写的,并且相同的单词仅以小写形式输入,则它被视为一个单独的单词。例如。如果输入了 book 和 BOOK,这些将被计为 2 个单独的单词。我曾尝试使用 .upper/.lower 函数,但这样做后没有办法将大写字母放回原处吗?我需要删除大写字母,然后再重新输入。

    def analyse_sentence():
       sentence=input("Please enter your sentence")
       sentence=sentence.split
       compression(sentence)

    def compression(sentence):
        positions=[]
        Unique_words=[]
    for i in sentence:
      if i not in unique:
         unique.append(i)
         positions.append(unique_words.index(i)+1)

【问题讨论】:

  • 复制一份并去掉副本中的大写字母。
  • 请提供您自己的代码示例以及究竟是什么导致了问题。正如@Marichyasana 所提到的,解决方案可能就像使用单独的参考一样简单,但目前还不清楚这是否可以在没有看到您自己的实现的情况下完成。
  • 你的输出应该是什么样子的?例如,它是一个字典,每个单词都有键,句子中的位置有值?
  • 句子和位置需要写入文件,然后从文件中取出并以原始大写字母打印到屏幕上,我是否将副本写入文件?
  • 我已在描述中放置了我的代码示例

标签: python


【解决方案1】:

在堆栈溢出时发布,您应该提供代码示例。 你有什么数据,你的代码是什么,它做了什么,你打算得到什么。 那么帮助你就容易多了。 无论如何,这是我帮助你的尝试:

text = 'blabla word1 word2 WORD word book BOOK bLaBlA'
unique_words =  list(set(text.lower().split(' ')))
print('text : %s' % text)
print('unique words : %s' % ','.join(unique_words))

编辑:

def analyse_sentence():
   sentence = input("Please enter your sentence")
   unique_words =  list(set(sentence.lower().split(' ')))
   print('sentence : %s' % sentence)
   print('unique words : %s' % ','.join(unique_words))
   return unique_words

【讨论】:

  • 我已将代码的开头放在描述中
  • 这只是以相反的顺序返回我的句子,每个单词之间都有点。我输入了“你好,为什么不”这个词,它返回的唯一词是:not.why.hello。一个
  • 你的句子是由独特的单词组成的,这很正常。 try : hello Hello HELLO why Not not Why,你会看到它只返回唯一的单词。
猜你喜欢
  • 1970-01-01
  • 2022-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-09
  • 2014-12-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多