【问题标题】:How do I get the numbers at the beginning of each line of a text file? [closed]如何获取文本文件每行开头的数字? [关闭]
【发布时间】:2017-02-08 23:26:15
【问题描述】:

我有一个 .txt 文件,其中包含许多行,即

230498soieung
3984sdgoij
032498eersn

如何访问此文本文件,然后获取这些数字的列表,即

230498, 3984, 032498

如果我能在 Python 中做到这一点,那就更好了。

【问题讨论】:

  • 向我们展示您的代码

标签: python string text text-processing


【解决方案1】:

使用re模块操作文本,可以使用\d+匹配多个数字,使用match()从头开始搜索。

import re
lines = ['230498soieung', '3984sdgoij', '032498eersn']
[re.match('\d+', line).group() for line in lines]

出来:

['230498', '3984', '032498']

【讨论】:

  • 可能会输入^,所以它只匹配行首,以防万一......
  • @kindall match() == search('^')
  • 哦,是的,总是很困惑。
猜你喜欢
  • 2017-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-07
相关资源
最近更新 更多