簡體   English   中英

如何在Python文件中計算單詞“ test”?

[英]How to count word “test” in file on Python?

我有一個包含許多字符串的文件。 看起來像

sdfsdf sdfsdfsdf sdfsdfsdf測試gggg uff測試測試fffffffff sdgsdgsdgsdg sdgsdgsdgsdg uuuttt 555555555 ddfdfdfg dddd4444 66677565 sdfsdfdgg5556

如何計算所有單詞“測試”。 我嘗試過,但是只有這個結果

f = open("file")
words =  0
for s in f:
    i = s.find('test')
    if i > -1:
        words += 1
print(words)
f.close()

並且此腳本僅計算包含單詞“ test”的字符串。 如何計算單詞?

如果要查找所有匹配項:

with open("file") as f:
    numtest = f.read().count("test")

如果只想查找單詞匹配項:

with open("file") as f:
    numtest = f.read().split().count("test")

單線:

s.split().count('test')

這應該工作。

   from collections import Counter
   with open('myfile.txt', 'r') as f:
       words = f.read().split()
       counts = Counter(words)

   print counts["test"] #counts just of exact string "test"
   #find all strings containing test (e.g 'atest', 'mytest')
   print sum([val for key,val in counts.iteritems() if "test" in key])

您可以使用正則表達式:

import re

with open('myfile.txt', 'r') as f:
    txt = f.read()

cnt = len(re.findall(r'\btest\b', txt))

如果您不關心區分大小寫(也可以匹配TestTEST

cnt = len(re.findall(r'\btest\b', txt, flags=re.I))

它將在整個文件中計算test的數量:

f = open('my_file.txt', 'r')
num_tests = len([word for word in f.read().split() if word == 'test'])
f.close()

請注意,它不會匹配tester, tested, testing, etc....單詞。如果您也想匹配它們,請改用:

f = open('my_file.txt', 'r')
num_tests = len([word for word in f.read().split() if 'test' in word])
f.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM