【问题标题】:How to check subsequent elements of string in python using iterators?如何使用迭代器检查python中字符串的后续元素?
【发布时间】:2018-05-01 21:33:34
【问题描述】:

我有一个句子要解析以检查某些条件:

a) 如果有一个句点,并且它后面是一个空格,然后是一个小写字母

b) 如果在没有相邻空格的字母序列中存在一个句点(即 www.abc.com)

c) 如果有一个句点后跟一个空格,后跟一个大写字母,前面是一个简短的标题列表(即先生、博士、夫人)

目前我正在遍历字符串(行)并使用 next() 函数来查看下一个字符是空格还是小写等。然后我只是循环遍历该行。但是我将如何检查 next, 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")

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

【问题讨论】:

  • 听起来你可能想使用正则表达式。
  • 我建议查看 Python 的 regex 文档和 Regex101 之类的在线游乐场。
  • 是否仍然可以在没有正则表达式的情况下实现它?

标签: python string parsing iterator


【解决方案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 简单工具在线生成和测试您的正则表达式

详细了解re library here

【讨论】:

    【解决方案2】:

    您可以使用多个下一步操作来获取更多数据

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

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

    【讨论】:

    • 但是如果我添加那一行,那么迭代器将前进,下次我进入循环时,它会比我想要的更早。我说的对吗?
    • 是的,这是正确的,这就是为什么我还建议将您的迭代保存在临时列表中
    猜你喜欢
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多