Skip to main content
 首页 » 编程设计

python之读取文本文件时出现ValueError : too many values to unpack,错误

2025年05月04日15hnrainll

我正在尝试打开一些文本文件,读取它们并从这些文件中获取 a-z 中的所有字符,并对这些字符进行更多处理。

但我收到错误 ValueError: too many values to unpack

这是我的脚本的开头,它在我收到错误的代码块的注释行上

for line in sys.stdin: 
 
    if ":" in line: 
 
        filename, line = line.strip().split(':') # this line gives error 

它似乎与拆分有关。我这样做的原因是因为我还想提取文件名并且我在标准输入读取文件之前在其他地方读取过,其格式为

filename.txt:文本文件中第一行的开始

我也在单个文本文件上尝试过这个并且它有效但是现在我尝试了完整的批处理我得到了这个

我这样从控制台调用它

grep -r '' susp-text | ./映射器.py |排序 | ./suspicious_reducer.py

错误在第一个脚本mapper.py

脚本的大图

#!/usr/bin/env python 
 
import sys 
import re 
 
# regular expressions 
 
pattern = re.compile("[a-zA-Z]*", 
                 re.MULTILINE | re.DOTALL | re.IGNORECASE) 
 
a_to_f_pattern = re.compile("[a-fA-F]", re.IGNORECASE) 
g_to_l_pattern = re.compile("[g-lG-L]", re.IGNORECASE) 
m_to_r_pattern = re.compile("[m-rM-R]", re.IGNORECASE) 
s_to_z_pattern = re.compile("[s-zS-Z]", re.IGNORECASE) 
 
# Read pairs as lines of input from STDIN 
for line in sys.stdin: 
    print line 
    if ":" in line: 
 
        filename, line = line.strip().split(':') 
        filename = filename.replace("source_text/", "") 
        filename = filename.replace("suspicious_text/", "") 
 
        # loop through every word that matches the pattern 
        for word in pattern.findall(line): 
            while i < len(word): 

从读取的第一个文本文件中提取

 Even without the 
nets, caught she will be, from sheer fatigue, (15) owing to the depth of the snow, which balls 
itself under her shaggy feet and clings to her, a sheer dead weight. 
 
 (11) Al. "to envelop the victims in the nets." 
 
 (12) Lit. "whatever the creature is in contact with inside." 
 
 (13) Cf. Aesch. "Prom." 87, {Poto tropo tesd' ekkulisthesei tukhes}. 
 
 (14) Or, "if the creature is not first suffocated in the snow itself." 
 
 (15) See Pollux, v. 50. "She must presently be tired out in the heavy 
    snow, which balls itself like a fatal clog clinging to the under 
    part of her hairy feet." 

请您参考如下方法:

听起来您的一行中可能包含多个“:”。在这种情况下,split 将返回一个包含两个以上项目的列表,这太多了,无法放入两个变量中。

尝试指定最大分割数额:

filename, line = line.strip().split(':', 1)