设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
查看: 5112|回复: 0
打印 上一主题 下一主题

英文单词排序答案

[复制链接]

3

主题

0

好友

29

积分

新手上路

Rank: 1

跳转到指定楼层
楼主
发表于 2013-8-18 15:57:46 |只看该作者 |倒序浏览
原始文件是这样的:
[work@sageskr python]$ cat from.txt
A bad beginning makes a bad ending. 恶其始者必恶其终。
Hello Mr.张,welcome you to 南京.


#==========程序==========
#!/bin/env python
# -*- encoding:utf-8 -*-
import re
fo = open('/home/work/python/from.txt')
ot = open('/home/work/python/ot.txt')
t_result = []
while True:
    line = fo.readline()
    if not line:
        fo.close()
        break
    else:
        line =  re.sub('[^A-Za-z]',' ',line)
        list_line = line.split()
        for i in list_line:
            t_result.appen(i)
def order_by_str(x):
    temp = []
    res = []
    for i in x:
        temp.append((i.lower(),i))
    temp.sort()
    for l in temp:
        res.append(l[1])
    return res
result = order_by_str(t_result)
for i in result:
    ot.write(i + "\n")
ot.close()
#==========程序结束==========

结果是这样的:
[work@sageskr python]$ cat ot.txt
A
a
bad
bad
beginning
ending
Hello
makes
Mr
to
welcome
you

发现结果中有些单词是重复的,怎么减少重复呢,做了下改良
=====start=====
#!/bin/env python
# -*- encoding:utf-8 -*-
import re
fo = open('/home/work/python/from.txt')
ot = open('/home/work/python/ot.txt','w')
t_result = []
while True:
    line = fo.readline()
    if not line:
        fo.close()
        break
    else:
        line =  re.sub('[^A-Za-z]',' ',line)
        list_line = line.split()
        for i in list_line:
            t_result.append(i)
def order_by_str(x):
    temp = []
    res = []
    _temp = []
    for i in x:
        temp.append((i.lower(),i))
    for k in temp:
        _temp.append(k[0])
    temp = set(_temp)
    temp = sorted(temp)
    for l in temp:
        res.append(l)
    return res   
result = order_by_str(t_result)
for i in result:
    ot.write(i + "\n")
ot.close()
=====end=====
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-5-13 16:08 , Processed in 0.015085 second(s), 22 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部