【问题标题】:python detect tab charpython检测标签字符
【发布时间】:2014-07-09 21:13:29
【问题描述】:

我试图在特定文件中拆分单词和整数。文件的字符串采用以下形式(包含 word 的行没有 '\t' char 但 int numbers(all positive) have): (有些词是包含'-'字符的数字,)

-1234
\t22
\t44
\t46
absv
\t1
\t2
\t4
... 

所以我的想法是通过将行的对象转换为浮动来拆分单词和字符串。

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

with codecs.open("/media/New Volume/3rd_step.txt", 'Ur') as file:#open file
    for line in file: # read line by line
        temp_buffer = line.split() # split elements
        for word in temp_buffer:
            if not('-' in word or not is_number(word)):
            ....

所以如果它是一个词,我会得到例外,如果不是那么它是一个数字。该文件是 50 Gb ,在中间的某个地方,文件格式似乎出了点问题。因此,拆分单词和数字的唯一可能方法是使用 \t 字符。但是我怎样才能检测到它呢?我的意思是我拆分行来获取字符串,这样我就丢失了特殊字符。

编辑:

我真的很傻很新很抱歉浪费了你的时间。看来我可以通过这种方式更轻松地找到它:

with codecs.open("/media/D60A6CE00A6CBEDD/InvertedIndex/1.txt", 'Ur') as file:#open file
    for line in file: # read line by line
    if not '\t' in line:
            print line

【问题讨论】:

    标签: python string split


    【解决方案1】:

    您应该尝试将您的参数指定为split(),而不是只使用默认值,即所有空格字符。除了\t 之外,您最初可以在所有空格上拆分它。试试这个:

    white_str = list(string.whitespace)    # string.whitespace contains all whitespace.
    white_str.remove("\t")                 # Remove \t
    white_str = ''.join(white_str)         # New whitespace string, without \t
    

    然后使用split(white_str) 代替split()。这将在除\t 之外的所有空格上拆分您的行以获取您的字符串。然后您可以稍后检测\t 以获得您需要的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-26
      • 1970-01-01
      • 2021-03-03
      • 2018-06-08
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多