文本文件冒号和空格分隔符

2024-09-28 23:50:23 发布

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

我有个档案wordTopic.txt和文件的格式为:

208:4 208:1 1049:2 3059:15 73684:10 715:15 6100:7 1129:15 1276:2 722:6 4809:1 726:15 6456:5 3703:10 1634:11 14342:13 13785:15 8930:6 61497:11 5435:15 327:1 327:1 228:8 7186:14 10229:2 13787:15 14683:3 437:7 1232:7 3272:15 127:15 9731:0 2367:6 957:8 957:8 810:15 11952:5 18459:5 35248:6 24209:6 19155:3 364:1 364:1 2550:15 7169:15 10939:15 35249:11 4039:8 21608:13 2612:7 1006:15 1113:15 87090:14 1423:8 2180:3 1375:15 270:9 2309:2 533:11 9204:15 660:16 17071:13 

上面是文件的一行,每行的长度不同

wordid:topicid wordid:topicid wordid:topicid........

我只希望主题ID存储在数组中。如何获取主题id(即)如何在冒号后存储数字。主题ID将仅从0到19。你知道吗


Tags: 文件txtid主题格式数字档案数组
3条回答

您可以为这样的行读取topicid

topic_ids = [el.split(':')[1] for el in row.split()]

你的问题不是很清楚,但我会在python中这样做:

假设这是一行,你可以读入:

result_list = []
for element in line.split():
    result_list.append(element.split(":")[-1]

这样,主题id将存储在一个列表中(python中类似数组的结构)

在Java中,您可以按以下方式执行:

    String text= "208:4 208:1 1049:2 3059:15 73684:10 715:15 6100:7 1129:15";

    List<Integer> topicIds = new ArrayList<Integer>();
    for (String str: text.split(" ")) {
        topicIds.add(Integer.parseInt(str.split(":")[1]));
    }

相关问题 更多 >