加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 按包含数字的行排序行,忽略附加到字母的数字

发布时间:2020-12-20 12:28:01 所属栏目:Python 来源:网络整理
导读:按包含数字的行排序行,忽略附加到字母的数字 我需要对文件中的行进行排序,使得包含至少一个数字(0-9)的行,在这些字母之一(“a”,“e”,“g”)之前不计数数字1-5,“i”,“n”,“o”,“r”,“u”,“v”或“u:”(u :))被移动到文件的末尾. 这是一个示例文件:
按包含数字的行排序行,忽略附加到字母的数字

我需要对文件中的行进行排序,使得包含至少一个数字(0-9)的行,在这些字母之一(“a”,“e”,“g”)之前不计数数字1-5,“i”,“n”,“o”,“r”,“u”,“v”或“u:”(u :))被移动到文件的末尾.

这是一个示例文件:

I want to buy some food.
I want 3 chickens.
I have no3 basket for the eggs.
I have no3 basket which can hold 24 eggs.
Move the king to A3.
Can you move the king to a6?

在示例文件中,以下是哪些匹配的注释:

I want to buy some food. % does not match
I want 3 chickens. % matches
I have no3 basket for the eggs. % does not match,because "3" is preceded by "o"
I have no3 basket which can hold 24 eggs. % matches,because contains "24"
Move the king to A3. % matches,words preceded by "A" are not ignored.
Can you move the king to a6? % matches,6 is not 1-5

输出会将所有匹配的行放在底部:

I want to buy some food.
I have no3 basket for the eggs.
I want 3 chickens.
Move the king to A3.
Can you move the king to a6?
I have no3 basket which can hold 24 eggs.

优选地(尽管不是必需的),解决方案将包含最大匹配数字的行分类到末尾.例如. “我有10只鸡和12只蝙蝠.”在“我有99只鸡”之后出现(4位数). (2位数).

使用BASH,Perl,Python 2.7,Ruby,sed,awk或grep的解决方案都很好.

解决方法

如果你的grep支持-P(perl-regexp)选项:

pat='(?<=[^0-9]|^)((?<!u:)(?<![aeginoruv])[1-5]|[06-9])'

{ grep -vP "$pat" input.txt; grep -P "$pat" input.txt; } >output.txt

如果你已经安装了(超级sed):

ssed -nR '
/(?<=[^0-9]|^)((?<!u:)(?<![aeginoruv])[1-5]|[06-9])/{
    H
    $!d
}
$!p
${
    g
    s/n//
    p
}' input.txt

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读