【发布时间】:2009-12-27 17:37:34
【问题描述】:
如何删除\n 和以下字母?非常感谢。
wordlist = ['Schreiben\nEs', 'Schreiben', 'Schreiben\nEventuell', 'Schreiben\nHaruki']
for x in wordlist:
...?
【问题讨论】:
如何删除\n 和以下字母?非常感谢。
wordlist = ['Schreiben\nEs', 'Schreiben', 'Schreiben\nEventuell', 'Schreiben\nHaruki']
for x in wordlist:
...?
【问题讨论】:
>>> import re
>>> wordlist = ['Schreiben\nEs', 'Schreiben', \
'Schreiben\nEventuell', 'Schreiben\nHaruki']
>>> [ re.sub("\n.*", "", word) for word in wordlist ]
['Schreiben', 'Schreiben', 'Schreiben', 'Schreiben']
通过re.sub完成:
>>> help(re.sub)
1 Help on function sub in module re:
2
3 sub(pattern, repl, string, count=0)
4 Return the string obtained by replacing the leftmost
5 non-overlapping occurrences of the pattern in string by the
6 replacement repl. repl can be either a string or a callable;
7 if a callable, it's passed the match object and must return
8 a replacement string to be used.
【讨论】:
[w[:w.find('\n')] fow w in wordlist]
很少测试:
$ python -m timeit -s "wordlist = ['Schreiben\nEs', 'Schreiben', 'Schreiben\nEventuell', 'Schreiben\nHaruki']" "[w[:w.find('\n')] for w in wordlist]"
100000 loops, best of 3: 2.03 usec per loop
$ python -m timeit -s "import re; wordlist = ['Schreiben\nEs', 'Schreiben', 'Schreiben\nEventuell', 'Schreiben\nHaruki']" "[re.sub('\n.*', '', w) for w in wordlist]"
10000 loops, best of 3: 17.5 usec per loop
$ python -m timeit -s "import re; RE = re.compile('\n.*'); wordlist = ['Schreiben\nEs', 'Schreiben', 'Schreiben\nEventuell', 'Schreiben\nHaruki']" "[RE.sub('', w) for w in wordlist]"
100000 loops, best of 3: 6.76 usec per loop
编辑:
上面的解决方案是完全错误的(参见 Peter Hansen 的评论)。这里是更正的:
def truncate(words, s):
for w in words:
i = w.find(s)
yield w[:i] if i != -1 else w
【讨论】:
RE=re.compile(…).sub 和[RE('', w)…] 可以获得小幅加速(~10 %):无需为每个单词寻找sub() 方法。
您可以使用正则表达式来做到这一点:
import re
wordlist = [re.sub("\n.*", "", word) for word in wordlist]
正则表达式 \n.* 匹配第一个 \n 以及后面可能出现的任何内容 (.*) 并将其替换为空。
【讨论】:
>>> wordlist = ['Schreiben\nEs', 'Schreiben', 'Schreiben\nEventuell', 'Schreiben\nHaruki']
>>> [ i.split("\n")[0] for i in wordlist ]
['Schreiben', 'Schreiben', 'Schreiben', 'Schreiben']
【讨论】: