试图使用strip()函数,但运行时出错

2024-05-19 13:59:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的文本文件,字符串表示文件路径,整数表示类类型,它们之间用空格分隔

FEA/1048_IEO_FEA_MD.mp4  3

FEA/1029_IWW_FEA_XX.mp4  3

FEA/1002_WSI_FEA_XX.mp4  3

FEA/1001_IWW_FEA_XX.mp4  3

在我的代码中,我想为不同的变量分配路径和标签,并将它们附加到列表中

def get_clip_list(self, cliplist_file):
    
    datalist = list(open(cliplist_file, 'r'))
    clips_with_label = []
    for data in datalist:
        path, label = data.strip('\n').split(' ')[0], int(data.strip('\n').split(' ')[1])
        clips_with_label.append({'path': path, 'label': label})
    return clips_with_label

我的错误是“ValueError:以10为基数的int()的文本无效:“”。我不确定这意味着什么,我所有的标签都是整数。谢谢你的帮助。谢谢


Tags: path路径datawith整数标签labellist
3条回答

数据行之间有空行,分隔为两个空格而不是一个空格。将文件转换为list时,空行将转换为'\n'。它们不能转换为int。当split时的两个空格将包含空字符串。只要去掉空行,把空格换成一个就行了。

或者,如果这不是一个选项,您可以添加一个空行机制并将split更改为任何空格。例如,将代码更改为:

def get_clip_list(cliplist_file):
    datalist = list(open(cliplist_file, 'r'))
    clips_with_label = []
    for data in datalist:
        if data == '\n':
            continue
        path, label = data.split()[0], int(data.split()[1])
        clips_with_label.append({'path': path, 'label': label})
    return clips_with_label

if语句检测空行,并且不带任何参数的split用任何空格分割

附言:我删除了你的strip('\n'),因为int可以将带有'\n'的字符串很好地转换为整数

>>> 'FEA/1048_IEO_FEA_MD.mp4  3'.strip('\n').split(' ')
['FEA/1048_IEO_FEA_MD.mp4', '', '3']

int('')将引发ValueError。使用:

>>> 'FEA/1048_IEO_FEA_MD.mp4  3'.strip('\n').split()
['FEA/1048_IEO_FEA_MD.mp4', '3'] 

你的主要问题是你在实际空间上分裂From the docs

If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']).

此外:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

*强调我的

因此,您只需要使用split()而不是split(' ')


关于代码的其他一些注意事项:

  • 根本不需要strip行,因为int()构造函数知道如何处理新行字符。例如:int(" 5 \n") == 5

  • 您两次调用split,这是浪费。叫它一次,然后unpack the result

  • 您还需要跳过空行以避免进一步的错误。为此,您可以使用strip

代码的修订版本:

def get_clip_list(self, cliplist_file):
    clips_with_label = []

    with open(cliplist_file) as file:
        for line in file:
            if line.strip():
                path, label = line.split()
                clips_with_label.append({'path': path, 'label': int(label)})
    return clips_with_label

相关问题 更多 >