相关疑难解决方法(0)

在Python中匹配组

Python中是否有一种方法可以访问匹配组而无需明确创建匹配对象(或另一种方式来美化下面的示例)?

这是一个澄清我的问题动机的例子:

遵循perl代码

if    ($statement =~ /I love (\w+)/) {
  print "He loves $1\n";
}
elsif ($statement =~ /Ich liebe (\w+)/) {
  print "Er liebt $1\n";
}
elsif ($statement =~ /Je t\'aime (\w+)/) {
  print "Il aime $1\n";
}
Run Code Online (Sandbox Code Playgroud)

翻译成Python

m = re.search("I love (\w+)", statement)
if m:
  print "He loves",m.group(1)
else:
  m = re.search("Ich liebe (\w+)", statement)
  if m:
    print "Er liebt",m.group(1)
  else:
    m = re.search("Je t'aime (\w+)", statement)
    if m:
      print "Il aime",m.group(1)
Run Code Online (Sandbox Code Playgroud)

看起来很尴尬(if-else-cascade,匹配对象创建).

python regex

45
推荐指数
3
解决办法
10万
查看次数

如何避免编写request.GET.get()两次才能打印出来?

我来自PHP背景,想知道是否有办法在Python中执行此操作.

在PHP中你可以像这样用一块石头杀死2只鸟:

代替:

if(getData()){
    $data = getData();
    echo $data;
}
Run Code Online (Sandbox Code Playgroud)

我可以做这个:

if($data = getData()){
    echo $data;
}
Run Code Online (Sandbox Code Playgroud)

您检查是否getData()存在,如果存在,则将其分配给一个语句中的变量.

我想知道在Python中是否有办法做到这一点?所以不要这样做:

if request.GET.get('q'):
    q = request.GET.get('q')
    print q
Run Code Online (Sandbox Code Playgroud)

避免写request.GET.get('q')两次.

python dictionary if-statement

41
推荐指数
3
解决办法
3万
查看次数

如何在Python中简洁地级联多个正则表达式语句

我的困境:我正在传递一个字符串,然后我需要执行大量的正则表达式操作.逻辑是如果在第一个正则表达式中匹配,做一件事.如果不匹配,请检查与第二个匹配并执行其他操作,如果不检查第三个,依此类推.我可以这样做:

if re.match('regex1', string):
    match = re.match('regex1', string)
    # Manipulate match.group(n) and return
elif re.match('regex2', string):
    match = re.match('regex2', string)
    # Do second manipulation
[etc.]
Run Code Online (Sandbox Code Playgroud)

然而,这感觉不必要地冗长,通常在这种情况下,这意味着有一个更好的方式,我要么忽略或不知道.

有没有人建议更好的方法来做到这一点(从代码外观角度,内存使用角度或两者兼而有之)?

python regex coding-style

13
推荐指数
2
解决办法
8367
查看次数

如何在python中整齐地处理几个regexp案例

所以我在python中得到了一些我需要使用regexp解析的输入.

目前我正在使用这样的东西:

matchOK = re.compile(r'^OK\s+(\w+)\s+(\w+)$')
matchFailed = re.compile(r'^FAILED\s(\w+)$')
#.... a bunch more regexps

for l in big_input:
  match = matchOK.search(l)
  if match:
     #do something with match
     continue
  match = matchFailed.search(l)
  if match:
     #do something with match
     continue
  #.... a bunch more of these 
  # Then some error handling if nothing matches
Run Code Online (Sandbox Code Playgroud)

现在我通常喜欢python因为它简洁而简洁.但这感觉很冗长.我希望能够做到这样的事情:

for l in big_input:      
  if match = matchOK.search(l):
     #do something with match     
  elif match = matchFailed.search(l):
     #do something with match 
  #.... a bunch more of these
  else
    # …
Run Code Online (Sandbox Code Playgroud)

python

5
推荐指数
1
解决办法
155
查看次数

标签 统计

python ×4

regex ×2

coding-style ×1

dictionary ×1

if-statement ×1