Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用迭代器检查python中字符串的后续元素?_Python_String_Parsing_Iterator - Fatal编程技术网

如何使用迭代器检查python中字符串的后续元素?

如何使用迭代器检查python中字符串的后续元素?,python,string,parsing,iterator,Python,String,Parsing,Iterator,我想分析一个句子来检查一些条件: a) 如果有一个句点,后跟一个空格和一个小写字母 b) 如果字母序列内部有一个句点,且没有相邻的空格(即www.abc.com) c) 如果有一个句号,后跟一个空格,后跟一个大写字母,前面有一个简短的标题列表(即Mr.,Dr.Mrs.) 目前,我正在遍历字符串(行)并使用next()函数查看下一个字符是空格还是小写,等等,然后我只是循环遍历该行。但是我如何检查下一个,下一个角色是什么呢?我怎样才能找到以前的那些呢 line = "This is line.1 w

我想分析一个句子来检查一些条件:

a) 如果有一个句点,后跟一个空格和一个小写字母

b) 如果字母序列内部有一个句点,且没有相邻的空格(即www.abc.com)

c) 如果有一个句号,后跟一个空格,后跟一个大写字母,前面有一个简短的标题列表(即Mr.,Dr.Mrs.)

目前,我正在遍历字符串(行)并使用next()函数查看下一个字符是空格还是小写,等等,然后我只是循环遍历该行。但是我如何检查下一个,下一个角色是什么呢?我怎样才能找到以前的那些呢

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

任何帮助都将不胜感激。谢谢。

您可以使用多个后续操作来获取更多数据

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

您可以通过将迭代保存到临时列表来获取以前的迭代

正则表达式是您想要的

由于要检查字符串中的模式,所以可以通过
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].*'
您可以使用简单的工具在线生成和测试正则表达式


更广泛地阅读
re
library

听起来您可能想使用regex。我建议您查看Python文档和类似的在线游乐场。是否仍然可以在没有regex的情况下实现它?但是如果我添加这一行,那么迭代器将前进,下次我进入循环时,它将前进得更远比我想的要多。我说的对吗?是的,这是正确的,这就是为什么我还建议将迭代保存在一个临时列表中