LoginSignup
2
1

More than 5 years have passed since last update.

TypeError: list indices must be integers, not str

Posted at

背景

論文公開サイトarxivのスクレイピングを行い、リストの中身を操作しようとしたら
TypeError: list indices must be integers, not str
上記のようなエラーが出てきました。。
ちなみにarxiv.pyをライブラリとして使用しました。

TypeError: list indices must be integers, not str

エラーが出ているのは以下の関数ということがわかりました。(resultにはキーワードで検索した論文10個がそれぞれのタイトルごとに文字列としてリストに入っています。)

sample.py
def prune_query_result(result):
    prune_keys = ['updated_parsed',
                  'published_parsed',
                  'arxiv_primary_category',
                  'summary_detail',
                  'author',
                  'author_detail',
                  'links',
                  'guidislink',
                  'title_detail',
                  'tags',
                  'id']


    for key in prune_keys:
        try:
            del result[key]
        except KeyError:
            pass

google翻訳にかけて見たところ、
TypeError:リストインデックスは、strではなく整数でなければなりません
あ、インデックスに文字列が指定されてしまっている。。

fixed.py
def prune_query_result(result):
    prune_keys = ['updated_parsed',
                  'published_parsed',
                  'arxiv_primary_category',
                  'summary_detail',
                  'author',
                  'author_detail',
                  'links',
                  'guidislink',
                  'title_detail',
                  'tags',
                  'id']

    for i in range(len(result)):
        for key in prune_keys:
            try:
                del result[i][key]
            except KeyError:
                pass

インデックスに整数を入れてあげるとうまくいきました!!

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1