简体   繁体   English

将句子中的单词更改为特殊字符

[英]Changing words on a sentence to special characters

I am trying to change some words in a sentence to special characters but I don't get the required output. 我正在尝试将句子中的某些单词更改为特殊字符,但没有得到所需的输出。 Also i have tried using the replace method which doesn't seen to replace everything but only the first word. 我也尝试过使用replace方法,该方法不会替换所有内容,而只会替换第一个单词。

new_sentence = ''
sentence = input('Enter your word:')

for char in sentence:
    if 'the' in sentence:
        new_sentence += '~'
    elif 'as' in sentence:
        new_sentence += '^'
    elif 'and' in sentence:
        new_sentence += '+'
    elif 'that' in sentence:
        new_sentence += '$'
    elif 'must' in sentence:
        new_sentence += '&'
    elif 'Well those' in sentence:
        new_sentence += '% #'
    else:
        new_sentence += sentence 
print(new_sentence)

This is what happens when i run it. 这是我运行它时发生的情况。

Enter your word:the as much and
~~~~~~~~~~~~~~~

You could store your character modifications in a dictionary and then apply them using replace() in a for loop, like so: 您可以将字符修改存储在字典中,然后在for循环中使用replace()应用它们,如下所示:

sentence = 'This is the sentence that I will modify with special characters and such'

modifiers = {'the': '~', 'as': '^', 'and': '+', 'that': '$', 'must': '&', 'Well those': '% #'}

for i, v in modifiers.items():
    sentence = sentence.replace(i, v)

Returns: 返回值:

This is ~ sentence $ I will modify with special characters + such

@rahlf23 has the right method, but just in case you wanted to work with your current implementation: @ rahlf23具有正确的方法,但以防万一您想使用当前的实现:

If you split the sentence into individual words, then iterate over those and check what the word itself is, instead of checking each character in the input string and checking whether any of the words to replace exist in the string, you'll be on the right track 如果将句子拆分成单个单词,然后遍历这些单词并检查单词本身,而不是检查输入字符串中的每个字符并检查字符串中是否存在要替换的单词,您将在正确的轨道上

for word in sentence.split():
    if word.lower() == 'the':
    new_sentence += '~'
    ...

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM