You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用np.loadtxt提取txt文件中整行最后一列的完整音节组?

解决提取txt文件中整行末尾多元素音节组的问题

你的问题根源在于np.loadtxt()默认会把所有空白字符(空格、制表符等)都作为列分隔符,所以每行中从第4个元素开始的音节会被拆成多个独立列,而你指定usecols=(0,1,2,3)只提取了第4个元素(索引3),自然只能拿到每个音节组的第一个字符。

下面提供两种可行的解决方案:

方法1:纯Python逐行读取处理(灵活易理解)

通过限制字符串分割次数,把每行前3个元素单独提取,剩下的内容作为完整的音节组:

import numpy as np

syl_array = []
try:
    # 用with语句自动管理文件关闭
    with open(syl_file, 'r') as fid:
        lines = fid.readlines()
    
    # 定义数组的数据类型
    dtype = [('a', 'i4'), ('b', 'f4'), ('c', 'f4'), ('d', 'U20')]
    syl_array = np.empty(len(lines), dtype=dtype)
    
    for idx, line in enumerate(lines):
        # split(maxsplit=3) 只分割前3个空格,剩下的内容保留为一个字符串
        parts = line.strip().split(maxsplit=3)
        if len(parts) >= 4:
            syl_array[idx]['a'] = int(parts[0])
            syl_array[idx]['b'] = float(parts[1])
            syl_array[idx]['c'] = float(parts[2])
            syl_array[idx]['d'] = parts[3]
except FileNotFoundError:
    print('File does not exist')
    return

labels = syl_array['a']
spurtStartTimes = syl_array['b']
spurtEndTimes = syl_array['c']
syllables = syl_array['d']
print(syllables)  # 输出:['d ih' 'k l ay n d' 'g ih']

方法2:使用numpy.genfromtxt结合自定义转换器

利用genfromtxt的converters参数,对目标列进行自定义合并处理:

import numpy as np

def merge_syllables(line_bytes):
    # 将字节流转成字符串,分割后合并末尾的音节内容
    line_str = line_bytes.decode('utf-8').strip()
    parts = line_str.split(maxsplit=3)
    return parts[3] if len(parts) >= 4 else ''

try:
    dtype = [('a', 'i4'), ('b', 'f4'), ('c', 'f4'), ('d', 'U20')]
    syl_array = np.genfromtxt(
        syl_file,
        dtype=dtype,
        converters={3: merge_syllables},  # 对索引3的列应用自定义转换
        usecols=(0, 1, 2, 3)
    )
except FileNotFoundError:
    print('File does not exist')
    return

syllables = syl_array['d']
print(syllables)  # 输出:['d ih' 'k l ay n d' 'g ih']

内容的提问来源于stack exchange,提问作者Sankara Bharadwaj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 04:52:37