Проблема: TypeError: объект 'float' не повторяется - PullRequest
0 голосов
/ 03 марта 2019

Я использую python 3.2.2 для Windows 7. Это часть моего code.it читает из файла Excel. Но когда я запускаю код, он просто печатает от 0 до 10 и выдает «TypeError: 'float'объект не повторяется ".Спасибо за любую помощь!

 pages = [i for i in range(0,19634)]


    for page in  pages:

 x=df.loc[page,["id"]]
 x=x.values
 x=str(x)[2:-2]
 text=df.loc[page,["rev"]]

 def remove_punct(text):
  text=''.join([ch.lower() for ch in text if ch not in exclude])
  tokens = re.split('\W+', text)
  tex = " ".join([wn.lemmatize(word) for word in tokens if word not in stopword])

  removetable = str.maketrans('', '', '1234567890')
  out_list = [s.translate(removetable) for s in tokens1] 
  str_list = list(filter(None,out_list)) 
  line = [i for i in str_list if len(i) > 1]

  return line

 s=df.loc[page,["rev"]].apply(lambda x:remove_punct(x))

 with open('FileNamex.csv', 'a', encoding="utf-8") as f:
     s.to_csv(f, header=False)

 print(s)

Это ошибка

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-54-c71f66bdaca6> in <module>()
     33   return line
     34 
---> 35  s=df.loc[page,["rev"]].apply(lambda x:remove_punct(x))
     36 
     37  with open('FileNamex.csv', 'a', encoding="utf-8") as f:

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
   3190             else:
   3191                 values = self.astype(object).values
-> 3192                 mapped = lib.map_infer(values, f, convert=convert_dtype)
   3193 
   3194         if len(mapped) and isinstance(mapped[0], Series):

pandas/_libs/src\inference.pyx in pandas._libs.lib.map_infer()

<ipython-input-54-c71f66bdaca6> in <lambda>(x)
     33   return line
     34 
---> 35  s=df.loc[page,["rev"]].apply(lambda x:remove_punct(x))
     36 
     37  with open('FileNamex.csv', 'a', encoding="utf-8") as f:

<ipython-input-54-c71f66bdaca6> in remove_punct(text)
     22 
     23  def remove_punct(text):
---> 24   text=''.join([ch.lower() for ch in text if ch not in exclude])
     25   tokens = re.split('\W+', text)
     26   tex = " ".join([wn.lemmatize(word) for word in tokens if word not in stopword])

TypeError: 'float' object is not iterable

Спасибо за любую помощь!

1 Ответ

0 голосов
/ 03 марта 2019

Вы пытаетесь применить функцию, которая повторяет text (что бы это ни было) - и вы вызываете ее, используя значение float.

float s не может быть повторен.Вы можете использовать text = str(text), чтобы сначала преобразовать любой ввод в текст - но, глядя на ваш код, я не решаюсь сказать, что это имело бы смысл.

Вы можете проверить, обрабатываете ли вы плавающий объект следующим образом:

def remove_punct(text):

     if isinstance(text,float): 
         pass   #    do something sensible with floats here
         return #    something sensible

     text=''.join([ch.lower() for ch in text if ch not in exclude])
     tokens = re.split('\W+', text)
     tex = " ".join([wn.lemmatize(word) for word in tokens if word not in stopword])

     removetable = str.maketrans('', '', '1234567890')
     out_list = [s.translate(removetable) for s in tokens1] 
     str_list = list(filter(None,out_list)) 
     line = [i for i in str_list if len(i) > 1]

     return line

Вы можете либо взяться за float через isinstance, либо получить вдохновение от Как в Python определить, является ли объект итеративным? о том, как определить, если вы предоставляете любой повторяем.Вы должны обращаться с не-итерациями по-другому.

...