Python:只保留字符串中的单词,每个单词都换行

时间:2012-08-13 03:34:53

标签: python regex string

我有一个大型文本文件,其中的文字中插入了数字和两种类型的字符,'|''.'。我在StackOverflow上搜索并找到了如何获取此字符串并仅保留字母。例如,如果

old_fruits='apple|0.00|kiwi|0.00|0.5369|-0.2437|banana|0.00|pear'

然后

re.sub("[^A-Za-z]","",old_fruits)

将返回

'applekiwibananapear'

我正在尝试将这些单词写入每行一个单词的文件,然后是换行符,然后是下一个单词,如:

apple
kiwi
banana
pear

任何想法或指向正确方向的人都会受到赞赏。

5 个答案:

答案 0 :(得分:1)

试试这个:

import re

old_fruits = 'apple|0.00|kiwi|0.00|0.5369|-0.2437|banana|0.00|pear'

with open('fruits.out', 'w') as f:
    fruits = re.findall(r'[^\W\d]+', old_fruits)
    f.write('\n'.join(fruits))

答案 1 :(得分:1)

您可以不使用正则表达式执行此操作。拆分管道字符上的字符串,使用生成器表达式和inbuild string.isalpha()函数来过滤掉那些只是字母字符的单词,并将它们连接起来形成最终输出:

old_fruits = 'apple|0.00|kiwi|0.00|0.5369|-0.2437|banana|0.00|pear'
words = (word for word in old_fruits.split('|') if word.isalpha())
new_fruits = '\n'.join(words)

print(new_fruits)

输出

apple
kiwi
banana
pear

根据需要(不写入文件,但我认为你能够应对)。

编辑:敲了一个快速脚本来提供正则表达式与非正则表达式的时序比较:

import timeit

# Setup - not counted in the timing so it doesn't matter we include regex for both tests
setup = r"""old_fruits = 'apple|0.00|kiwi|0.00|0.5369|-0.2437|banana|0.00|pear'
import re
fruit_re=re.compile(r'[^\W\d]+')
"""

no_re = r"""words = (word for word in old_fruits.split('|') if word.isalpha())
new_fruits = '\n'.join(words)"""

with_re = r"""new_fruits = '\n'.join(fruit_re.findall(old_fruits))"""

num = 10000

print("Short input")
t = timeit.timeit(no_re, setup, number=num)
print("No regex: {0:.2f} microseconds to run".format((t*1e6)/num))
t = timeit.timeit(with_re, setup, number=num)
print("With regex: {0:.2f} microseconds to run".format((t*1e6)/num))

print("")
print("100 times longer input")

setup = r"""old_fruits = 'apple|0.00|kiwi|0.00|0.5369|-0.2437|banana|0.00|pear'*100
import re
fruit_re=re.compile(r'[^\W\d]+')"""

t = timeit.timeit(no_re, setup, number=num)
print("No regex: {0:.2f} microseconds to run".format((t*1e6)/num))
t = timeit.timeit(with_re, setup, number=num)
print("With regex: {0:.2f} microseconds to run".format((t*1e6)/num))

我的电脑上的结果:

Short input
No regex: 18.31 microseconds to run
With regex: 15.37 microseconds to run

100 times longer input
No regex: 793.79 microseconds to run
With regex: 999.08 microseconds to run

因此预编译的正则表达式在短输入字符串上更快,对于更长的表达式,生成器表达式更快(至少在我的计算机上 - Ubuntu Linux,Python 2.7 - 结果可能因您而异)。

答案 2 :(得分:0)

以OP的代码为基础:

import re
old_fruits = 'apple|0.00|kiwi|0.00|0.5369|-0.2437|banana|0.00|pear'

with open('outdata.txt', 'w') as f:
    f.write('\n'.join(re.sub("[^A-Za-z]"," ",old_fruits).split()))

给出

apple
kiwi
banana
pear
文件'outdata.txt'中的

答案 3 :(得分:0)

答案并不那么难,虽然我不知道这是否是最佳做法,但为什么不呢

print re.sub("[^A-Za-z]+","\n",old_fruits) #re.sub("[^A-Za-z]+","\n",old_fruits) is the string you want

“+”表示非字母字符的1 +个实例将替换为\ n

答案 4 :(得分:0)

of=old_fruits.split("|")
for i in range(0,len(of),2):
 # write to file