【问题标题】:Replacing specific word in text with uppercase version of itself [duplicate]用自己的大写版本替换文本中的特定单词[重复]
【发布时间】:2019-06-14 13:43:42
【问题描述】:

好的,所以这应该不是那么困难,但我正在画一个空白。所以,这个程序的想法是它找到只在文本中出现一次的单词,然后将它们大写。这是完整的代码:

from collections import Counter
from string import punctuation

path = input("Path to file: ")
with open(path) as f:
    word_counts = Counter(word.strip(punctuation) for line in f for word in line.replace(")", " ").replace("(", " ")
                      .replace(":", " ").replace("", " ").split())

wordlist = open(path).read().replace("\n", " ").replace(")", " ").replace("(", " ").replace("", " ")

unique = [word for word, count in word_counts.items() if count == 1]

for word in unique:
    text = wordlist
    text.replace(word, str(word.upper()))

print(text)

它只打印常规文本,不做任何修改。

事实上,我知道第一部分有效,这只是给我带来麻烦的最后一个 for 循环。

知道我在搞砸什么吗?

【问题讨论】:

    标签: python python-3.x string replace


    【解决方案1】:

    替换此行

    text.replace(word, str(word.upper()))
    

    text = text.replace(word, str(word.upper()))
    

    string.replace() 不修改原始字符串实例。

    【讨论】:

    • 啊哈。非常感谢,我会尽快接受它作为答案!
    • 好的,还有一件事。当预期的输出应该是Genesis 37:1 Jacob lived In the land of his father's SOJOURNINGS, in the land of Canaan. 时,它会打印GenesIs 37:1 Jacob lIved In the land of hIs FATher's SOJOURNINGS, In the land of Canaan. 我相信这是因为大写字母出现在其他关键字中。有没有办法解决这个问题?
    • 请使用最小的工作示例为此打开一个新问题。
    【解决方案2】:

    您应该将其分配回文本。

    text = text.replace(word, str(word.upper()))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-20
      • 2011-09-06
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 2014-08-24
      • 2022-12-11
      • 1970-01-01
      相关资源
      最近更新 更多