【问题标题】:Python: Sorting the contents of a .txt file in numerical order that contains symbolsPython:按包含符号的数字顺序对 .txt 文件的内容进行排序
【发布时间】:2016-07-13 23:04:05
【问题描述】:

我有一个文本文件,其中每行包含一个整数,以及诸如 \|: 之类的随机字符。我想对它们进行数字排序。

我目前知道如何在文件中只使用整数。

import csv
import operator

sample = open('sampledata.txt')

csv1 = csv.reader(sample)

sort = sorted(csv1, key=lambda x : int(x[0]))
for eachline in sort:
    print eachline

文本文件示例:

:279::
     ::123::/\  \
      ::562::___
  ::482::  |:|  |
::183::
 ::528::     ___

我需要什么代码才能忽略这些字符。

任何帮助将不胜感激

【问题讨论】:

    标签: python sorting csv numerical


    【解决方案1】:

    而不是只解析第一个字符的int(x[0]),而是获取所有数字字符,然后将它们与int(''.join(c for c in x if c.isdigit()))结合起来。

    【讨论】:

      猜你喜欢
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      相关资源
      最近更新 更多