Skip to main content
 首页 » 编程设计

python之TypeError : expected string or buffer with re. 匹配和 matchObj.group()

2024年10月25日10me-sa

我不断收到错误:

Traceback (most recent call last): 
  File "ba.py", line 13, in <module> 
    matchObj = re.match(r"^(\w+ \w+) batted (\d+) times with (\d+) hits and (\d+) runs", line) 
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 137, in match 
    return _compile(pattern, flags).match(string) 
TypeError: expected string or buffer  
  1. line应该使用line.strip读取文件中的每一行

  2. re.match 使用正则表达式查找与 3 个组(players、hits, atBats) 在字符串中

  3. matchObj.group() 应该读取每个组并将统计数据放在 playerStats{} 中的位置字典

如何让 re.match 将类型归因于 matchObj,以便我可以使用 group() 拉取并添加到 playerStats()?

   import re, sys, os 
 
if len(sys.argv) < 2: 
    sys.exit("Usage: %s filename" % sys.argv[0]) 
 
filename = sys.argv[1] 
 
if not os.path.exists(filename): 
    sys.exit("Error: File '%s' not found" % sys.argv[1]) 
 
playerStats = {'players': (0, 0, 0)}  
 
matchObj = re.match(r"^(\w+ \w+) batted (\d+) times with (\d+) hits and (\d+) runs", line) 
 
with open(filename) as f: 
    for line in f: 
        line = line.strip() 
 
    if player in playerStats: 
        playerStats[players][0] += atBat 
        playerStats[players][1] += hit 
 
    if player not in players: 
        player = matchObj.group(1) 
        playerStats[players][0] = atBat 
        playerStats[players][1] = hit 
        avgs = 0 
 
    else:  
        playerStats[players] = player 
        playerStats[players][0] = atBat 
        playerStats[players][1] = hit 
        playerStats[players][2] = 0 
 
    try: 
        player = matchObj.group(1) 
        atBat = matchObj.group(2) 
        hit = matchObj.group(3) 
 
        except AttributeError as ae: 
            print str(ae), "\skipping line:", line 
        except IndexError as ie: 
            print str(ie), "\skipping line:", line 
 
#calculates averages 
    for players in playerStats: 
        avgs[player] = round(float(hits[player])/float(atBats[player]), 3)  
 
    print "%s: %.3f" % (player, avgs[player]) 

请您参考如下方法:

您正在将整个文件读入行。你得到那个错误是因为 line 是一个列表而不是一个字符串或缓冲区。如果您循环遍历每一行,请将您的 strip 放在 for 循环中。下面的示例可帮助您入门。

with open(filename) as f: 
    for line in f: 
        line = line.strip() 
        matchObj = re.match(r"^(\w+ \w+) batted (\d+) times with (\d+) hits and (\d+) runs", line) 
        #Rest of your code here. Also Use try except to catch AttributeError and IndexError 
        try: 
            player = matchObj.group(1) 
            atBat = matchObj.group(2) 
            hit = matchObj.group(3) 
            #Other stuff 
        except AttributeError as ae: 
            print str(ae), "\skipping line:", line 
        except IndexError as ie: 
            print str(ie), "\skipping line:", line 

此外,除非您显示文本文件中的示例数据,否则我无法判断您的正则表达式是否准确。

更新: 这是一个基于您的评论和更新的工作版本。根据需要随意修改:

#hard code file name for simplicity 
filename = "in.txt" 
    #Sample item: 'players': (0, 0, 0) 
    playerStats = {} 
 
    with open(filename) as f: 
        for line in f: 
            line = line.strip() 
            #Match object should be here, after you read the line 
            matchObj = re.match(r"^(\w+ \w+) batted (\d+) times with (\d+) hits and (\d+) runs", line) 
 
            try: 
                player = matchObj.group(1) 
                atBat = matchObj.group(2) 
                hit = matchObj.group(3) 
                runs = matchObj.group(4) 
 
                #Bad indent - Fixed 
                #You should put data against player, there is no players variable. 
                #initialize all stats to 0 
                if player not in playerStats: 
                    playerStats[player] = [0, 0, 0] 
 
                playerStats[player][0] += int(atBat) 
                playerStats[player][1] += int(hit) 
                playerStats[player][2] += int(runs) 
 
            except AttributeError as ae: 
                print str(ae), "skipping line:", line 
            except IndexError as ie: 
                print str(ie), "skipping line:", line 
 
    #calculates average hits 
    avgs = {} 
    for player in playerStats: 
        hitsOfplayer = playerStats[player][1] 
        atBatsOfPlayer = playerStats[player][0] 
        avgs[player] = round(float(hitsOfplayer)/float(atBatsOfPlayer), 3) 
        print "%s: %.3f" % (player, avgs[player]) 

in.txt 的内容:

Mr X batted 10 times with 6 hits and 50 runs 
Mr Y batted 12 times with 1 hits and 150 runs 
Mr Z batted 10 times with 4 hits and 250 runs 
Mr X batted 3 times with 0 hits and 0 runs 
junk data 
junk data 2 

输出:

'NoneType' object has no attribute 'group' skipping line: junk data 
'NoneType' object has no attribute 'group' skipping line: junk data 2 
Mr Y: 0.083 
Mr X: 0.462 
Mr Z: 0.400