2012-01-04 39 views
0

我想檢查文本中是否包含「0」的文本。python。如何查找文本是否包含零。?

我不能使用字符串.__包含(「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. 

希望你明白我的問題? 感謝

+0

答案爲止告訴你如何說,如果有字符串中的某處是一個0,但是,因爲你說「2560」將被忽略,是你想要的嗎? – 2012-01-04 10:26:02

+0

是裏卡多..這正是我想要的。是否可以使用字符串搜索方法? – AGeek 2012-01-04 10:27:29

回答

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 

正則表達式方法可能更快,所以根據您的工作負載和性能目標可能值得研究。

+0

是的,我也只剩下這個選擇了...因爲我認爲沒有其他選擇可用。 – AGeek 2012-01-04 10:35:40

+0

我們是否可以使用strip函數在其中提供正則表達式......如果我們想剝離以某些字母開頭的行的部分,並且我們想要去掉那個 – AGeek 2012-01-04 10:41:38

+0

不,請不要使用正則表達式。在尋找像這樣的非常簡單的情況下,評估正則表達式通常很慢。 – 2012-01-04 10:43:39

0

有很多方法找到這個在Python ...

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

是一個選項,你可以打開「0」到一個變量,使之更加通用。

正則表達式也許是可取的。但真的是過度殺傷。

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'] 
+0

這就是我在上面的問題中所說的,我想過也是這樣做的。但是沒有其他技術可用。 – AGeek 2012-01-04 10:29:22

+0

「in」運算符更適合於在字符串中搜索單個字符。 – Spencer 2012-01-04 10:29:53

+0

這是要走的路。與其他解決方案不同,它會匹配由標點符號等非空格詞邊界劃定的「0」。 OP的問題清楚地表明,他們不想接受字符串,其中'0'字符出現在更大的數字中。 – 2012-01-04 10:31:42

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" 
0

如果你正在尋找什麼是公正的 「0」,則:

string == '0' 

如果有可能是空白各地:

string.strip() == '0' 
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") 
相關問題