我试图在特定文件中拆分单词和整型数。文件的字符串是这样的形式(包含word的行没有'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)):
....
如果它是一个单词,我会得到异常,如果不是,那么它是一个数字。文件是50gb,在中间的某个地方,文件的格式似乎出了问题。因此,分割单词和数字的唯一可能方法是使用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
稍后为您需要的。