【问题标题】:Python re.findall() purpose in this code此代码中的 Python re.findall() 用途
【发布时间】:2016-12-22 14:42:37
【问题描述】:

我目前正在学习 Python,我正在尝试破译我在网上找到的代码。代码的重点是将原始字符串与用户输入键进行比较,如果匹配,则返回原始字符串。

我无法理解 re.findall() 在这段代码中的作用

所以 head[0] 包含一个数据字符串

('2016-12-22 06:28:36', u'Kith x New Era K 59FIFTY Cap - Pink', 你'http://kithnyc.com/products/kith-x-new-era-59fifty-cap-pink')

键包含一个原始字符串

key=r'Nike|Ultra'

head = self.data
for k in key:
    print k
    flag=re.findall(k,str(head[0]),flags=re.I)
    print len(flag)
    if len(flag)>4:
        print head[0]

据我了解,这段代码的目的是遍历key,看是否匹配head[0]。如果匹配,则返回 head[0]。但是还是返回了,head[0]

('2016-12-22 06:28:36', u'Kith x New Era K 59FIFTY Cap - Pink', 你'http://kithnyc.com/products/kith-x-new-era-59fifty-cap-pink')

即使它不匹配。

【问题讨论】:

  • 上面的sn-p中好像没有return的声明。
  • 对不起,我没有包括那个。我正在对其进行测试,只是打印了“已发送”。我现在编辑了代码
  • 我认为我们不了解您的需求。也许您只想返回/打印head 中与key 正则表达式匹配的那些项目?
  • 如果key = r'Nike|Ultra' 然后循环键将循环字符串的每个字符,也许尝试key=[r'Nike|Ultra']
  • 是的。如果匹配键正则表达式,则假设在 head 中打印项目。但这是我在网上找到的代码,我试图理解为什么作者决定这样做。还是我有错误的想法,这根本不是作者的目的?

标签: python regex python-2.7


【解决方案1】:

如果匹配键正则表达式,则假设打印头中的项目。

然后使用following code

import re
head = ('2016-12-22 06:28:36', 'nike item', 'ultra item', 'Kith x New Era K 59FIFTY Cap - Pink', 'http://kithnyc.com/products/kith-x-new-era-59fifty-cap-pink')
key=r'Nike|Ultra'  # This is a regex pattern, matches `Nike` or `Ultra` 
for s in head:     # Iterate the items in head
    if re.search(key, s, flags=re.I): # Search for a match in each item, case insensitively
        print(s)  # Print if found

输出:nike itemultra item

在您的代码中,您使用for k in key: 循环遍历模式的字符。使用re.findall,搜索所有非重叠匹配项以匹配k 中的单个字符,并且仅检查head[0],不考虑所有其他项。

【讨论】:

    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    相关资源
    最近更新 更多