蟒蛇。如何查找文本是否包含零。

时间:2012-01-04 10:18:19

标签: python

我想在一段文本中检查该文本是否包含“0”。

我不能使用字符串.__包含(“0”),因为这是错误的编码,或者如果我可以使用它,我没有足够的积分回到我的大四,这是唯一的方法。或者,如果你能让我知道一些观点?

我们发现的另一种方法是从每一行中提取,然后提取no。从中,将其转换为整数,然后检查该值是否大于0.但这很少耗费时间。

该字符串可能包含2560之类的值,在此搜索中应忽略该值。

请告诉我一些替代方案。我不想要整数转换。

请帮忙。

例如

abc : 1234
def : 1230  >>> This kind of text should return False

abc : 1234
def : 0  >>>> This kind of text should return True, as it contains 0.

希望您了解我的问题? 感谢

6 个答案:

答案 0 :(得分:3)

起初,我认为你可以使用in

if "0" in myString:
  print "%s contains 0" % myString

然而,在重新阅读您的问题时,这似乎不是您想要做的。这将检测连续的0,例如:

abc: 200

我想你不想这样做。你需要使用更复杂的东西。我可能会使用一些简单的手动代码,而不是使用不同答案中建议的正则表达式。方法如下:

def is_row_zero(row):
  parts = row.split(":")
  value = parts[1].strip()
  if value == "0":
    print "%s is 0, not allowed" % parts[0]
    return True
  return False

正则表达式方法可能更快,因此可能值得根据您的工作量和性能目标进行调查。

答案 1 :(得分:2)

使用正则表达式查找模式:

>>> import re
>>> re.findall('\W(0)\W', 'alsdkjf 0 asdkfs0asdf   0   ')
['0', '0']

\W(0)\W匹配零,其中包含非字母数字字符('\ W')。

你的例子:

>>> re.findall('\W(0)\W', 'abc : 1234 def : 1230 ')
[]
>>> re.findall('\W(0)\W', 'abc : 1234 def : 0 ')
['0']

答案 2 :(得分:0)

有许多方法可以在Python中找到它...

if " 0 " in [string variable]:
    do something...

是一个选项,您可以将“0”变为变量以使其更通用。

也许正则表达式可能更可取。但真的有点矫枉过正。

答案 3 :(得分:0)

如果我正确阅读了您的问题,输入就是一个文本文件,如:

label : value
label : value
...

我建议您逐行阅读文件并使用正则表达式:

for line in open("filename.txt"):
    if re.match(r"\S+ : 0$", line):
        print "The row's value is zero"

或使用.endswith

for line in open("filename.txt"):
    if line.endswith(" 0"):
         print "The row's value is zero"

答案 4 :(得分:0)

如果你要找的只是“0”,那么:

string == '0'

如果可能是空白:

string.strip() == '0'

答案 5 :(得分:0)

你的问题并不完全清楚,只有当它不是数字的一部分时你才想要零吗? 您可以检查字符串中的所有0,并查看其相邻字符是否为数字。

等等:

def has_zero(s):
    if "0" not in s:
        return False
    if s=="0":
        return True
    if s[0]=="0" and not s[1].isdigit():
        return True
    if s[-1]=="0" and not s[-2].isdigit():
        return True
    return any(s[i]=="0" and not (s[i-1].isdigit() or s[i+1].isdigit()) for i in range(1,len(s)-1))

print has_zero("hell0 w0rld")
#True
print has_zero("my number is 2560")
#False
print has_zero("try put a zer0 in here with number 100")
#True
print has_zero("0")
print has_zero("10")
print has_zero("01")
print has_zero("a0")
print has_zero("0a")
print has_zero("00")