简体   繁体   English

python如何检查和替换字符串中的单词?

[英]python how to check and replace words in string?

I'm new to python and I'm trying to make a function which is able to detect if a string has the words "I", "I'm", "My", "Was", "Our", "me" replace it with "You", "You're", "Your", "Were", "Your" and "You" and also add a question mark at the end if it did not end with any punctuation. 我是python的新手,正在尝试创建一个函数,该函数能够检测字符串中是否包含单词“ I”,“ I'm”,“ My”,“ Was”,“ Our”,“ me” ”,将其替换为“您”,“您”,“您”,“是”,“您”和“您”,并且如果末尾没有标点符号,请在末尾添加问号。 So far I have the code 到目前为止,我有代码

if ' ' in statement and statement[-1].isalpha() is True:
       response = statement
       response = response + "?"

       return response

but I'm not sure how to make the function seach for those words and replace with their opposites. 但是我不确定如何对这些单词进行功能搜索并用相反的单词替换。 For example if the statement was "My dog said I'm happy" its response should be "Your dog said you're happy?" 例如,如果声明为“我的狗说我很高兴”,则其回答应为“您的狗说您很高兴?”。

thanks 谢谢

create a dictionary mapping and iterate over it, something like this 创建一个字典映射并对其进行迭代,就像这样

d = {"I": "You", "I'm": "You're".....}
for k,v in d.iteritems():
    statement = statement.replace(k, v)

Check out python's replace function, which replaces in a string... 检出python的replace函数,该函数将替换为一个字符串...

eg 例如

x = "My dog said I'm happy"
x.replace("My", "Your") # "Your dog said I'm happy"

You could make a list of old being the list of words to replace and a list new being what to replace with, and then successively replace. 您可以将old列表作为要替换的单词列表,将new列表作为要替换的单词列表,然后依次替换。

Note that you should replace longer words before shorter words. 请注意,您应该在较短的单词之前替换较长的单词。

For example if you replace "I" with "You" in the above, you'll get "Your dog said You'm happy". 例如,如果在上面用“您”替换“我”,您将得到“您的狗说您很高兴”。 Hence you should replace "I'm" before "I". 因此,您应该 “ I” 之前替换“ I'm”。

This has been asked many , many times before. 这已经被问很多很多之前倍。 You'll want to use some variation of the replace method from Python's Standard Library . 您将要使用Python 标准库中的replace方法的一些变体。

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

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