需要拆分由多个分隔符分隔的文件内容并显示最长的行

时间:2018-06-05 06:31:04

标签: python

input.txt中

hi all.i hope all are doing well?
please help with the solution.i tried all the possible solution?

预期o / p:

['hi all','i hope all are doing well,
 'please help with the solution','i tried all the possible solution']

2 个答案:

答案 0 :(得分:0)

要获得快速解决方案,您可以尝试以下代码。但我建议你看一下python的re模块。非常方便。

import re

result = []
pattern = re.compile('[,.?]')

with open('input.txt') as f:
    for line in f.readlines():
        r = re.split(pattern, line.strip())
        if r:
            result.append(r)


print result

答案 1 :(得分:0)

另一个解决此问题的简单方法是使用Split方法。我试图尽可能简单地解决它。

>>> spam = ['Alice', 'ants', 'Bob', 'badgers', 'Carol', 'cats']
>>> spam.sort()
>>> spam
['Alice', 'Bob', 'Carol', 'ants', 'badgers', 'cats']