2014-02-19 41 views
0

这两行来自执行维基百科短语搜索的程序,并返回特定短语发生的总次数。搜索包含撇号至关重要:将变量插入文本搜索字符串

results = w.search("\"of the cat's\"", type=ALL, start=1, count=1) 
print results.total 

我想用一个变量替换单词“cat”,例如,

q = "cat" 

这样我就可以为不同的单词列表生成相同的搜索格式。请如何格式化搜索字符串以包含变量?

+0

这stringformatting问题已经问了很多次。例如。这里http://stackoverflow.com/questions/5082452/python-string-formatting-vs-format – deinonychusaur

回答

0

首先,Python有一些有用的字符串方法,我觉得这对你很有帮助。在这种情况下,我们将使用format函数。另外,不要我被'" s吓倒。你可以简单地用反斜杠将它们转义出来。演示:

>>> a = '\'' 
>>> a 
"'" 

看看单引号是如何夹在这些双引号之间?

你可以做同样的双引号:

>>> a = "\"" 
>>> a 
'"' 
>>> 

现在回答你的问题,你可以使用自带的串类.format功能(无需进口)。

让我们来看一看:

>>> a = "{}\'s hat" 
>>> a.format("Cat") 
"Cat's hat" 
>>> a.format("Dog") 
"Dog's hat" 
>>> a.format("Rat") # Rats wear hats? 
"Rat's hat" 
>>> 

在你的情况,你可以简单地这样做:

w.search("\"of the {}'s\"".format(<your animal here>), type=ALL, start=1, count=1) 
0

使用Python,你可以简单地做:

q = "cat" 
results = w.search("\"of the " + q + "'s\"", type=ALL, start=1, count=1) 
print results.total 

还有

q = "cat" 
results = w.search("\"of the %s's\"" & q, type=ALL, start=1, count=1) 
print results.total 

而且

q = "cat" 
results = w.search("\"of the {query}'s\"".format(query=q), type=ALL, start=1, count=1) 
print results.total 

看到这个post了更详细的讨论,包括性能。