简体   繁体   English

python 2.7,在open('file.txt')上使用Counter

[英]python 2.7, using Counter on open('file.txt')

I got a good answer before for a similar problem but I didnt consider the scalability of the question that I asked. 对于类似的问题,我之前得到了很好的答案,但是我没有考虑我提出的问题的可扩展性。 I had trouble with the text editor I am using concerning pasting in large amounts of text and ending up with either newlines, or if I remove all the newlines from the document then the text goes off the screen and wont allow me to scroll to the end. 我在使用文本编辑器时遇到了麻烦,涉及粘贴大量文本并以换行符结尾,或者如果我从文档中删除了所有换行符,则文本不显示在屏幕上,并且不允许我滚动到末尾。 So I saw how to use open on the text as a file but now the code wont work properly. 所以我看到了如何在文本上使用open作为文件,但是现在代码无法正常工作。
Here is the code: 这是代码:

import sys 
import os
from collections import Counter
def main():
    with open('garbledText.txt') as text:
        print [k for k,v in Counter(text).items() if v<3]
if __name__=='__main__':
    main()

it seemed like it was going in the right direction because if I change 'v<3' to 'v<1' I get an empty list, but with 'v<3' I get all the chars. 好像是朝着正确的方向前进,因为如果我将“ v <3”更改为“ v <1”,我将得到一个空列表,但是如果使用“ v <3”,我将得到所有字符。
what I am trying to do is parse the 'garbledText.txt' to find chars that appear 1-2 times. 我想做的是解析“ garbledText.txt”以查找出现1-2次的字符。

replace text for text.read(), the first make a collection of lines and the second of caracters. text.read(),替换text text.read(),第一个集合行,第二个集合字符。

from collections import Counter

def main():
    with open('garbledText.txt') as text:
        collection = Counter(text.read())
    print [char for char, times in collection.items() if times < 3]

if __name__=='__main__':
    main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM