[英]Is there a ways I can replace some specific words to some specific words?
我知道这是一个非常基本的问题,可以用.replace 做(但我认为我必须做很多的.replace),对我来说,有没有更清洁的方法可以做到这一点,因为我还在学习Python,我对这门语言还不太了解,请见谅。 (每当我搜索“如何用一个词替换一个词时,它只显示.replace方法,所以我不知道是否有另一种方法。)
替换可以做什么:
我在 W3schools 上读过这个例子
txt = "I like bananas"
x = txt.replace("bananas", "apples")
但是我想要的是,有时在1个输入中,我可能会写JS
,它将成为Javascript
, p
,它将成为Python
fb
Facebook
.有很多词我想把它从快捷词替换成正确的词
我可以以某种方式使用 1 个变量,但它存储某种“快捷方式单词”,然后用 1 个正确存储单词的变量替换它吗?
例如:
shortcutWord = {js, fb, p}
properlyWord = {Javascript, Facebook, Python}
而且它会明白,js适用于Javascript,fb适用于Facebook等,具体不知道怎么形容,但是有没有办法呢? 谢谢。
这回答了你的问题了吗?
您只需要输入 2 个并行的 arrays 具有快捷方式和长字。 这可以通过使用字典更好地编写,但是,我假设您需要两个并行的 arrays。
shortcut_word = ["js", "fb", "p"]
properly_word = ["Javascript", "Facebook", "Python"]
txt = "I like js and i use fb"
def properfySentence(txt, shortcuts, full_words):
words = txt.split(' ') # split the sentence into an array of words
for word in words: # loop through the words...
if word in shortcuts: # and check if the word is in the shortcuts
words[words.index(word)] = full_words[shortcuts.index(word)] # replace the shortcut with the full length word
txt_changed = ' '.join(words) # rejoin the words with spaces
return txt_changed # return the result
print(
properfySentence(txt,shortcut_word,properly_word)
)
您可以使用以下语法:
txt = "I like FB"
x = txt.replace({'js': 'javascript', 'fb': 'facebook', 'FB' : 'Facebook' })
print(x)
您可以基于 re 模块(正则表达式)创建一个 replace() function,利用其用 function 或 lambda 替换模式的能力:
import re
def replace(s,d):
pattern = r"\b("+"|".join(map(re.escape,sorted(d,key=len)[::-1]))+r")\b"
return re.sub(pattern,lambda m:d[m.group()],s)
subs = {"js":"javascript","fb":"Facebook","py":"Python"}
text = "I love py but I despise js and fb"
print(replace(text,subs))
I love Python but I despise javascript and Facebook
该模式是使用 pipe ( |
) 运算符到 select 字典中的任何关键字(包含在\b(...)\b
中以搜索整个单词)形成的。 替换 function 使用 key 从字典中获取对应的替换值。 关键字按长度递减排序,因为 pipe 运算符不是贪婪的,如果存在作为较长关键字前缀的较短关键字,我们希望它找到较长的关键字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.