【问题标题】:Is there a way to escape the error and go to the next word?有没有办法逃避错误并转到下一个单词?
【发布时间】:2021-09-22 18:01:01
【问题描述】:

我运行此代码并遇到以下错误: 我怎样才能摆脱错误并继续下一个单词?

GLOVE_DATASET_PATH = 'glove.840B.300d.txt'

from tqdm import tqdm
import string
embeddings_index = {}
f = open(GLOVE_DATASET_PATH, encoding="utf8")
word_counter = 0
for line in tqdm(f):
  values = line.split()
  word = values[0]
  if word in dictionary:
    coefs = np.asarray(values[1:], dtype='float32')
    embeddings_index[word] = coefs
  word_counter += 1
f.close()

print('Found %s word vectors matching enron data set.' % len(embeddings_index))
print('Total words in GloVe data set: %s' % word_counter)

错误信息是 ValueError: could not convert string to float: '.'在线 ---> 12 coefs = np.asarray(values[1:], dtype='float32')

【问题讨论】:

  • 打印line,内容可能不是你所期望的。

标签: python


【解决方案1】:

你可以压制它:

from contextlib import suppress
with suppress(ValueError):
    coefs = np.asarray(values[1:], dtype='float32')

【讨论】:

【解决方案2】:

当某事发生时,我会尝试找出正在发生的事情:

  if word in dictionary:
      try: 
          coefs = np.asarray(values[1:], dtype='float32')
      except:
          print(values[1:], type(values[1:]))
          coefs = 0
      embeddings_index[word] = coefs

这将打印出你得到的回报,无法转换,此时还会在你的列表中写一个0

【讨论】:

  • 感谢您的回复!这完美地工作并解决了问题。 :)
  • 如果答案是您想要的,请接受。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-08
  • 2010-10-14
  • 2020-09-15
相关资源
最近更新 更多