【问题标题】:Regex Pattern Matching -a substring in words in CSV File正则表达式模式匹配 - CSV 文件中单词中的子字符串
【发布时间】:2020-11-08 02:26:59
【问题描述】:
'Neighborhood,eattend10,eattend11,eattend12,eattend13,mattend10,mattend11,mattend12,mattend13,
hsattend10,hsattend11,hsattend12,hsattend13,eenrol11,eenrol12,eenrol13,menrol11,menrol12,
menrol13,hsenrol11,hsenrol12,hsenrol13,aastud10,aastud11,aastud12,aastud13,wstud10,wstud11,
wstud12,wstud13,hstud10,hstud11,hstud12,hstud13,abse10,abse11,abse12,abse13,absmd10,absmd11,
absmd12,absmd13,abshs10,abshs11,abshs12,abshs13,susp10,susp11,susp12,susp13,farms10,farms11,
farms12,farms13,sped10,sped11,sped12,sped13,ready11,ready12,ready13,math310,math311,math312,
math313,read310,read311,read312,read313,math510,math511,math512,math513,read510,read511,read512,
read513,math810,math811,math812,math813,read810,read811,read812,read813,hsaeng10,hsaeng11,
hsaeng12,hsaeng13,hsabio10,hsabio11,hsabio12,hsabio13,hsagov10,hsagov11,hsagov13,hsaalg10,
hsaalg11,hsaalg12,hsaalg13,drop10,drop11,drop12,drop13,compl10,compl11,compl12,compl13,
sclsw11,sclsw12,sclsw13,sclemp13\

我有这个数据集。我需要知道有多少 drop 字并打印出来。

或类似的任何单词,如mattend 并打印出来。

我尝试使用findall,但我认为这不正确

我假设我们可以使用re.searchre.match。 如何在 RegEx 中做到这一点?

【问题讨论】:

    标签: python-3.x regex pattern-matching


    【解决方案1】:

    您可以在re.findall() 上使用len() 来获取返回列表的长度:

    import re
    with open('example.csv') as f:
      data = f.read().strip()
    print(len(re.findall('drop',data)))
    

    【讨论】:

    • 谢谢,但它只显示匹配的子字符串。我也想打印字符串,drop13,drop12,drop23,这就是我尝试从上面的答案中做到这一点的方法,re.findall("drop\d*", str) 但我收到了错误expected string or bytes-like object。你介意纠正一下吗?
    • @kirtipurohit 如果然后使用原始字符串 re.findall(r'drop\d*', str) 并且请避免使用 str 作为变量名
    【解决方案2】:

    我认为re.findall 应该是正确的。 来自 python re 模块文档:

    搜索:

    扫描字符串,寻找这个正则表达式产生匹配的第一个位置,并返回一个对应的匹配对象。

    匹配:

    如果字符串开头的零个或多个字符匹配此正则表达式,则返回对应的匹配对象。

    找到:

    返回字符串中所有不重叠的模式匹配,作为字符串列表。从左到右扫描字符串,并按找到的顺序返回匹配项。如果模式中存在一个或多个组,则返回组列表;如果模式有多个组,这将是一个元组列表。结果中包含空匹配项。

    我在您的示例中进行了尝试,它对我有用: re.findall("drop", str)

    如果您想在它后面看到数字,您可以尝试以下操作: re.findall("drop\d*", str)

    如果您想计算可以使用的单词: len(re.findall("drop\d*", str))

    【讨论】:

    • 我收到一个错误:预期的字符串或类似字节的对象
    • with open('exg.csv','r') as file: data=file.read().split(',') 我将所有这些 csv 数据类型转换为字符串类型,但错误仍然存​​在
    猜你喜欢
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 2014-07-09
    • 2016-12-03
    • 2011-11-08
    • 1970-01-01
    • 2016-12-06
    相关资源
    最近更新 更多