[英]How to filter all words, which contain N or more characters?
我想处理一个文本文件,以查找包含超过N个字符的所有单词。 欢迎使用Bash(grep,awk)或Python(re)中的任何解决方案! 但是,最短的是首选。
egrep -o '[^ ]{N,}' <filename>
查找所有至少N
字符长的非空格构造。 如果您担心“单词”,可以尝试[a-zA-Z]
。
#!/usr/bin/env python
import sys, re
def morethan(n, file_or_string):
try:
content = open(file_or_string, 'r').read()
except:
content = file_or_string
pattern = re.compile("[\w]{%s,}" % n)
return pattern.findall(content)
if __name__ == '__main__':
try:
print morethan(*sys.argv[1:])
except:
print >> sys.stderr, 'Usage: %s [COUNT] [FILENAME]' % sys.argv[0]
用法示例(通过此要点 ):
$ git clone -q git://gist.github.com/763574.git && \
cd 763574 && python morethan.py 7 morethan.py
['stackoverflow', 'questions', '4585255', 'contain', ...
蟒蛇
import fileinput
N = 5
for line in fileinput.input():
for word in line.split():
if len(word) > N:
print word
import re; [s for s in re.findall(r"\w+", open(filename, "r").read()) if len(s) >= N]
输出的单词长度大于5,且行号
awk -F ' ' '{for(i=1;i<=NF;i++){ if(length($i)>=6) print NR, $i }}' your_file
您可以使用简单的grep,但它将返回整行:
grep '[^ ]\{N\}'
其中N是您的电话号码。
我不知道如何在grep或awk中获得单个单词,但是在Python中很简单:
import re
f = open(filename, 'r')
text = f.read()
big_words = re.findall('[^ ]{N,}', s)
同样,N是您的电话号码。 big_words将是包含您的单词的列表。
在此示例中,将5
替换为您要查找的长度。 第二个示例将其显示为一个函数
1)
>>> import re
>>> filename = r'c:\temp\foo.txt'
>>> re.findall('\w{5}', open(filename).read())
['Lorem', 'ipsum', 'dolor', 'conse', 'ctetu', 'adipi', 'scing', 'digni', 'accum', 'congu', ...]
2)
def FindAllWordsLongerThanN(n=5, file='foo.txt'):
return re.findall('\w{%s}' % n, open(file).read())
FindAllWordsLongerThanN(7, r'c:\temp\foo.txt')
re.findall(r'\w'*N+r'\w+',txt)
尝试这个:
N = 5 #Threshold
f = open('test.txt','r')
try:
for line in f.xreadlines():
print " ".join([w for w in line.split() if len(w) >= N])
finally:
f.close()
为了完整性(尽管在这种情况下,regexp解决方案可能更好):
>>> from string import punctuation
>>> with open('foreword.rst', 'rt') as infile:
... for line in infile:
... for x in line.split():
... x = x.strip(punctuation)
... if len(x) > 5:
... print x
假设您的意思是“过滤器”,即每个单词应打印几次。 如果您只想每个单词一次,我可以这样做:
>>> from string import punctuation
>>> result = set()
>>> with open('foreword.rst', 'rt') as infile:
... for line in infile:
... for x in line.split():
... x = x.strip(punctuation)
... if len(x) > 5:
... if x not in result:
... result.add(x)
... print x
你好,我相信这是具有lambda函数的不错的solutino。 第一个参数是N
import sys
import os
def main():
p_file = open("file.txt")
t= lambda n,s:filter(lambda t:len(t)>n,s.split())
for line in p_file:
print t(3,line)
if __name__ == '__main__':
main()
纯重击:
N=10; set -o noglob; for word in $(<inputfile); do ((${#word} > N)) && echo "$word"; done; set +o noglob
如果输入文件不包含任何通配符( *
, ?
, [
),则可以省略set
命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.