【问题标题】:Is there a way in Python to read text file token-by-token?Python中有没有办法逐个读取文本文件?
【发布时间】:2021-06-18 10:18:20
【问题描述】:

我需要处理一个 BIG 文本文件,其中包含以 ASCII 表示的空格分隔的浮点数:

1.0012 0.63 18.201 -0.7911 92.2869 ...

如何使用内置 Python 工具逐一读取这些数字(不是整个文件,也不是逐行)? 作为示例,解决此任务的 C 源代码如下所示:

float number;
FILE *f = fopen ("bigfile.txt", "rt");
while (!feof (f)) {
    fscanf (f, "%f", &number);
    /* ... processing the number here ... */
}
fclose (f);

【问题讨论】:

标签: python file


【解决方案1】:

您可以尝试逐个字符读取文件,将块大小指定为1,然后识别一个单词是否完整。

with open('file', 'r') as openedFile:
    for chunk in iter(partial(openedFile.read, 1), b''):
        ...

有用的链接:

https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects

【讨论】:

    【解决方案2】:

    如果逐行解决方案不可行(例如,文件只有一大行),您可以使用 read(size=1) 一次读取一个字符。

    你可以这样做:

    current = ""
    with open("file.txt") as f:
        while True:
            char = f.read(1)
            if char == "":
                # Reached EOF
                break
            elif char.isdecimal():
                current += char
            else:
                num = float(current)
                # process num however you like
                current = ""
    

    【讨论】:

      【解决方案3】:

      您应该能够一次只读取一行,然后split() 每行以获取数字标记:

      with open('file.txt') as f:
          lines = f.readlines()
      
      for line in lines:
          tokens = line.split()
          for token in tokens:
              # process number here
      

      【讨论】:

      • 但问题是,OP 指定了空格分隔的值,没有提到换行符。
      • @AnnZen 我的回答应该对单行文件仍然有效。
      • 我知道,但它会变成“读入整行并随后拆分”,而 OP 想逐渐读入。
      【解决方案4】:

      您可以尝试使用str.isspace() 方法来检查空格:

      nums = ['0']
      char = ' '
      with open('file.txt', 'r') as f:
          while char:
              char = f.read(1)
              if nums[-1][-1].isspace():
                  nums.append(char)
              else:
                  nums[-1] += char
      nums = list(map(float, nums))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-08-04
        • 1970-01-01
        • 2019-09-20
        • 2020-11-17
        • 1970-01-01
        • 2018-06-10
        • 1970-01-01
        相关资源
        最近更新 更多