【问题标题】:filtering strings of particular length from file从文件中过滤特定长度的字符串
【发布时间】:2013-06-28 15:56:07
【问题描述】:

我有一个包含内容的 foo.txt 文件

'w3ll' 'i' '4m' 'n0t' '4sed' 't0' 

'it'

我正在尝试提取其中包含 2 个字符的所有单词。我的意思是,输出文件应该只有

4m
t0
it

我尝试的是,

with open("foo.txt" , 'r') as foo:
    listme = foo.read()

string =  listme.strip().split("'")

我想这将用 ' 符号分割字符串。 如何仅选择那些字符数等于 2 的撇号中的那些字符串?

【问题讨论】:

    标签: python string file python-2.7 extract


    【解决方案1】:

    这应该可行:

    >>> with open('abc') as f, open('output.txt', 'w') as f2:
    ...     for line in f:
    ...         for word in line.split():    #split the line at whitespaces
    ...             word = word.strip("'")   # strip out `'` from each word
    ...             if len(word) == 2:       #if len(word) is 2 then write it to file
    ...                 f2.write(word + '\n')
    
    print open('output.txt').read()
    4m
    t0
    it
    

    使用regex

    >>> import re
    >>> with open('abc') as f, open('output.txt', 'w') as f2:
        for line in f:
            words = re.findall(r"'(.{2})'",line)
            for word in words:
                f2.write(word + '\n')
    ...             
    >>> print open('output.txt').read()
    4m
    t0
    it
    

    【讨论】:

    • @abhikafle 有什么错误吗?请在问题正文中发布此类示例,而不是在 cmets 中,因为它们不可读。
    • 谢谢@Ashwini。但是正则表达式方法将两个用逗号分隔的不同字符串作为一个。当我运行代码找到 20 个字符时。 word ,它给了我 "', 9, '1186148119', ''" 作为输出,它仍然有效,但它由许多不同的字符串组成,而不仅仅是一个。
    • @abhikafle 您的示例输入输入不包含任何 ',' 这就是我没有处理它们的原因。请自行发布此类问题。
    • 能否添加','作为标记来分隔两个字符串?
    • @abhikafle 在第一个代码中将line.split() 替换为line.split(', ')
    【解决方案2】:
    with open("foo.txt" , 'r') as file:
      words = [word.strip("'") for line in file for word in line.split() if len(word) == 4]
    
    with open("out", "w") as out:
      out.write('\n'.join(words) + '\n')
    

    【讨论】:

      【解决方案3】:

      假设您要查找包含在 '' 符号中的所有单词,它们正好是两个字符长:

      import re
      split = re.compile(r"'\w{2}'")
      
      with open("file2","w") as fw:
          for word in split.findall(open("file","r").read()):
                  fw.write(word.strip("'")+"\n")
      

      【讨论】:

        【解决方案4】:

        由于您正在阅读以空格(或逗号)分隔的引用单词,您可以使用 csv 模块:

        import csv
        
        with open('/tmp/2let.txt','r') as fin, open('/tmp/out.txt','w') as fout:
            reader=csv.reader(fin,delimiter=' ',quotechar="'")
            source=(e for line in reader for e in line)             
            for word in source:
                if len(word)<=2:
                    print(word)
                    fout.write(word+'\n')
        

        'out.txt':

        i
        4m
        t0
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-03-03
          • 1970-01-01
          • 2021-03-03
          • 1970-01-01
          • 1970-01-01
          • 2021-12-27
          • 2020-09-03
          相关资源
          最近更新 更多