2017-11-18 419 views
0

我有,我想分析檢查一些條件句:如何使用迭代器檢查python中的字符串的後續元素?

a)如果有一個週期,它是在一個空格後跟一個小寫字母

b)若存在是一個沒有相鄰空白的字母序列的內部時間(即,www.abc.com)

c)如果有句點後跟一個空格,後跟一個大寫字母,並在前面加上一個簡短的標題列表(即先生,太太博士)

目前我通過串(線)迭代,並使用下一個()函數看到下一個字符是空格或小寫,等於是我只是通過線環。但是,我怎麼會檢查看下一個,下一個角色會是什麼?我如何找到以前的?

line = "This is line.1 www.abc.com. Mr." 

t = iter(line) 
b = next(t) 

for i in line[:len(line)-1]: 
    a = next(t) 
    if i == "." and (a.isdigit()): #for example, this checks to see if the  value after the period is a number 
     print("True") 

任何幫助,將不勝感激。謝謝。

+0

聽起來像是你可能需要使用正則表達式來測試你的正則表達式。 –

+0

我建議你檢查出Python的[正則表達式(https://docs.python.org/3/howto/regex.html)文檔和在線操場像[Regex101(https://regex101.com/)。 – excaza

+0

是否有可能仍然實現它沒有正則表達式? – ce1

回答

0

您可以使用多個下操作,以獲得更多的數據

line = "This is line.1 www.abc.com. Mr." 

t = iter(line) 
b = next(t) 

for i in line[:len(line)-1]: 
    a = next(t) 
    c = next(t) 
    if i == "." and (a.isdigit()): #for example, this checks to see if the  value after the period is a number 
     print("True") 

可以通過保存你的迭代到一個臨時目錄

+0

但如果我再補充一點線,則迭代器將提前,下一次我來到這個循環將進一步提前,比我想。我對麼? – ce1

+0

是的,這是正確的,這就是爲什麼我也建議保存你的迭代在臨時列表中 – mduiker

1

正則表達式是你想要的得到以前的。

因爲你去檢查一個字符串的模式,您可以通過re圖書館利用Python的正則表達式內建支持。

例子:

#To check if there is a period internal to a sequence of letters with no adjacent whitespace 
import re 
str = 'www.google.com' 
pattern = '.*\..*' 
obj = re.compile(pattern) 
if obj.search(str): 
    print "Pattern matched" 

同樣生成你想要在你的字符串來檢查條件的模式。

#If there is a period and it is followed by a whitespace followed by a lowercase letter 
regex = '.*\. [a-z].*' 

可以生成並使用網上this簡單的工具

更廣泛地瞭解rehere

相關問題