【问题标题】:Remove only trailing whitespace from output从输出中仅删除尾随空格
【发布时间】:2023-03-16 14:13:01
【问题描述】:

我有一个分配给我的家庭作业任务。基本上问题是:

编写一个可以去掉品牌名称并用通用名称替换它们的程序。

下表显示了一些具有通用名称的品牌名称。该映射也已在您的程序中作为BRANDS 字典提供给您。

BRANDS = {
  'Velcro': 'hook and loop fastener',
  'Kleenex': 'tissues',
  'Hoover': 'vacuum',
  'Bandaid': 'sticking plaster',
  'Thermos': 'vacuum flask',
  'Dumpster': 'garbage bin',
  'Rollerblade': 'inline skate',
  'Asprin': 'acetylsalicylic acid'
}

这是我的代码:

sentence = input('Sentence: ')

sentencelist = sentence.split()
for c in sentencelist:
  if c in BRANDS:
    d = c.replace(c, BRANDS[c])
    print(d, end=' ')
  else:
    print(c, end=' ')

我的输出:

Sentence: I bought some Velcro shoes.
I bought some hook and loop fastener shoes.  

预期输出:

Sentence: I bought some Velcro shoes.
I bought some hook and loop fastener shoes.

看起来一样,但在我的输出中,'shoes.' 之后有一个额外的空格,而本来不应该有空格。那么如何删除这个空格呢?

我知道你可以这样做 rstrip()replace() 我试过了,但是当我只需要删除尾随空格而不删除任何其他空格时,它只会把所有东西混在一起。如果用户将品牌名称放在句子的中间,而我使用rstrip(),它将把品牌名称和句子的其余部分连接在一起。

【问题讨论】:

  • 你在 'sentencelist = sentence.split()' 行之前尝试过 'sentence = sentence.rstrip()' 吗?
  • print(d, end=' ') 也在您在句子中打印的最后一行的末尾添加一个空格
  • @kkblue:那没意义;没有参数的str.split()(或None 的显式拆分参数)已经隐式去除了前导和尾随空格以及在空格运行时的拆分。

标签: python replace removing-whitespace


【解决方案1】:

您的 end=' ' 无条件地在您的输出中附加额外的空格。没有一致的方法可以撤消此操作(回显退格字符仅适用于终端,搜索仅适用于文件等)。

诀窍是一开始就避免打印它:

sentence = input('Sentence: ')

sentencelist = sentence.split()
result = []
for c in sentencelist:
    # Perform replacement if needed
    if c in BRANDS:
        c = BRANDS[c]  # c.replace(c, BRANDS[c]) is weird way to spell BRANDS[c]
    # Append possibly replaced value to list of results
    result.append(c)

# Add spaces only in between elements, not at the end, then print all at once
print(' '.join(result))
# Or as a trick to let print add the spaces and convert non-strings to strings:
print(*result)

【讨论】:

    【解决方案2】:

    关键是使用字符串的join 方法为您连接所有内容。例如,要在一堆字符串之间放置一个空格而不在最后一位之后放置空格,请这样做

    ' '.join(bunch_of_strings)
    

    字符串必须在一个可迭代的(如列表)中才能起作用。你可以这样列出清单:

    edited_list = []
    for word in sentence_list:
        if word in BRANDS:
            edited_list.append(BRANDS[word])
        else:
            edited_list.append(word)
    

    一个更短的选择是

    edited_list = [BRANDS.get(word, word) for word in sentence_list]
    

    无论哪种方式,您都可以使用join方法组合编辑后的句子:

    print(' '.join(edited_list))
    

    这是 Python,您可以在不使用中间列表的情况下将整个事情作为单行来完成:

    print(' '.join(BRANDS.get(word, word) for word in sentence_list))
    

    最后,您可以使用 splat 表示法加入 print 本身。在这里,您可以将列表中的每个元素作为单独的参数传入,并使用默认的 sep 参数插入空格:

    print(*edited_list)
    

    顺便说一句,d = c.replace(c, BRANDS[c]) 完全等同于 d = BRANDS[c]。由于字符串是不可变的,因此无论何时您执行c.replace(c, ...,您都只是在以某种难以辨认的方式返回替换对象。

    【讨论】:

    • 鉴于它是printing,你可以完全避免' '.joinprint(*(BRANDS.get(word, word) for word in sentence_list))(唯一真正的改进是如果迭代包含非字符串,print 将为你转换; 这主要只是一个有趣的选择)。
    • @ShadowRanger。我在其中添加了类似的内容。也可以使用完整列表,因为 splat 最终会存储整个生成器
    • 是的,尽管同样的论点适用于' '.joinwhich calls PySequence_Fast on the input,因此任何非list、非tuple 输入无论如何都会转换为list) .诚然,在这种情况下,它是一个实现细节(它可以用他们写的io.StringIO之类的东西来实现,随着扩展摊销,他们只是没有)。
    【解决方案3】:

    您不必拆分单词并遍历它。

    试试这个代码,它会工作,不会再出现空白问题

    sentence  = ' '.join(str(BRANDS.get(word, word)) for word in input_words)
    

    在这里,列出名称“input_words”并添加您要处理的行数

    学习愉快!

    【讨论】:

      【解决方案4】:

      问题是print(c, end=' ') 总是会在c 之后打印一个空格。这是一个非常小的更改来解决这个问题:

      sentence = input('Sentence: ')
      
      sentencelist = sentence.split()
      is_first = True
      for c in sentencelist:
          if not is_first:
              print(' ', end='')
          is_first = False
          if c in BRANDS:
              d = c.replace(c, BRANDS[c])
              print(d, end='')
          else:
              print(c, end='')
      

      正如其他人所指出的,这可以整理,例如,d = c.replace(c, BRANDS[c]) 等同于d = BRANDS[c],如果将其更改为c = BRANDS[c],则可以使用单个print 调用而不使用@ 987654328@子句。

      但是你也必须小心你的方法,因为像“我买了一个胡佛”这样的句子会失败。 sentence.split() 操作将保留“Hoover”。作为单个项目,由于额外的时间段,这将无法通过c in BRANDS 测试。您可以尝试将单词与标点符号分开,但这并不容易。另一种解决方案是将所有替换应用于每个元素,或者等效地应用于整个句子。这在这种情况下应该可以正常工作,因为您可能不必担心可能嵌入较长单词中的替换单词(例如,意外替换嵌入 'caterpillar' 中的 'cat')。所以这样的事情可能会正常工作:

      new_sentence = sentence
      for brand, generic in BRANDS.items():
          new_sentence = new_sentence.replace(brand, generic)
      print(new_sentence)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-15
        • 2016-02-29
        • 2015-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多