我试图在特定文件中拆分单词和整数。文件的字符串采用这些形式(包含单词的行没有 '\t' 字符,但 int 数字(全部为正数)有): (有些单词是包含'-'字符的数字,)
-1234
\t22
\t44
\t46
absv
\t1
\t2
\t4
...
所以我的想法是通过将行的对象转换为 float 来拆分单词和字符串。
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
最佳答案
您应该尝试为 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
以获取您需要的内容。
关于python检测标签字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24663912/