【问题标题】:Find numbers of 8 characters inside a txt file在 txt 文件中查找 8 个字符的数字
【发布时间】:2018-10-16 21:52:33
【问题描述】:

我有一个大小为 1 兆字节的文本文件,其中包含一些数字字符串和一些字符长度为 3、5、9、8、10 的字母字符串。我怎样才能找到所有只有长度的数字8个字符?在找到长度为 8 个字符的数字后,必须将这些数字提取并保存在这个文件 extract.txt 中。我该怎么做?

示例...

文件.txt

91664356
1665
00643
qouytyi
15790008
1567065
abcdeigf
qoiyytgxf
931467846
00851685
150033561246788
074226899

extracted.txt

91664356
15790008
15670654
00851685

【问题讨论】:

  • 不是正则表达式?
  • 您能否提供输入文本文件中的一些示例数据/行,包括“8 个字符数字”的正负命中?是否接受 int、hex、bin、float、...的数字格式?
  • example.txt 91664356 1667065/150037085/15670685/156790008/156790006/1567065/156706/15003706/156706/15003706/156039806/3858506/303785/3856039303853785>>
  • 数了好几遍,但1567065的长度好像只有七。你说with the length of 8。请澄清。
  • 15670657 已修正,长度为 8

标签: python dev-c++


【解决方案1】:

使用 -

with open('data.txt', 'r') as myfile:
    data=myfile.read()

numbers = re.findall(r'\D(\d{8})\D', data)

它将捕获长度为 8 的数字 - 包括像 478319.3 这样的数字

它将输出这些数字的列表。

示例

123.32 is a good number 12 also 12345678 478319.3

是文件的内容。 输出将是 -

['12345678']

【讨论】:

  • {8,8}而不是{8}的任何原因?
  • @DeepSpace 只是一种灵活性,因此如果用户稍后决定检测长度在 8-10 个字符之间的数字,他可以这样做。使用{8} 可能不会让阅读此代码的人导致这种情况
  • 另外,这将为字符串if you have a very long number it will match the first 8 digits, for example 123456781234提供错误的输出,这将提取12345678
  • @DeepSpace 你是对的,我已经修改了正则表达式,现在按照 OP 的建议捕获 8 位长度的数字
【解决方案2】:

像这样的源文件? 12345678 123456789 1234567 abcdefg abcdefgh abcdefghi 那么,也许这个脚本可以帮助你

f = open('stack.txt')
s = open('save.txt','w')
for i in f.read().split(' '):
    if(len(i)!=8):
        continue
    else:
        try:
            print(int(i))#if not number,int() will make an error
            s.write(i)
        except:
            pass
f.close()
s.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-14
    • 2018-10-26
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多