【问题标题】:List manipulation with Python使用 Python 进行列表操作
【发布时间】:2014-08-23 15:30:37
【问题描述】:

我有一个巨大的 JSON 文件,其中包含文章的标题和正文,如下所示。

{
    "paragraphs": [
        "Ismael Omar Guelleh, known in Djibouti by his initials, IOG, won a second term in a one-man presidential race in 2005 and a third term in April 2011.", 
        "Parliament - which does not include any representatives of the opposition - approved an amendment to the constitution in 2010 allowing the president to run for a third term.", 
        "The constitutional reforms also cut the presidential mandate to five years from six, and created a senate.", 
        "Mr Guelleh succeeded his uncle and Djibouti's first president, Hassan Gouled Aptidon, in April 1999 at the age of 52. He was elected in a multi-party ballot.", 
        "Mr Guelleh supports Djibouti's traditionally strong ties with France and has tried to reconcile the different factions in neighbouring Somalia."
    ], 
    "description": "A profile of Djibouti's political leader, President Guelleh", 
    "title": "Djibouti profile"
},

我想要做的是每次我将标题及其相应的段落附加到列表时,我想包含有四个或更多段落的标题(即我上面发布的示例有 5,所以我希望它包括在内)。我尝试用以下方式打印段落长度:

print len(y['paragraphs']

它可以工作,但我不能使用它来控制将要附加的内容。

我在 Python 中使用此代码:

titles = []
vocabulary = []
paragraphs = []

with open("/Users/.../file.json") as j:
data = json.load(j)


for x in range(0,len(data)):
    titles.append(data[x]['title'])
    paragraphs.append(data[x]['paragraphs'])

for y in range(3000, 3500):
   # here I believe there must be an if statement
    vocabulary.append(titles[y])
    vocabulary.append(paragraphs[y][0])
    vocabulary.append(paragraphs[y+1][0])

我尝试在第二个 for like 之后添加 if 语句:

if len(y['paragraphs']) > 4:

我得到了这个错误: TypeError:“int”对象没有属性“getitem

我知道解决方案是简单的一行代码,但我被卡住了。有什么想法吗?

谢谢!

【问题讨论】:

  • range(3000, 3500) 在做什么?
  • 我用它来获取条目 3000 和 3500 之间的标题和段落(它将上升到 3499)。如果您在上面看到,我首先将 JSON 中我需要的所有数据附加到列表标题和段落中。

标签: python json list if-statement


【解决方案1】:

您在for 循环中定义y

for y in range(3000, 3500):

这意味着y 将采用30003001、...3499 的值。这些都是int 的值。因此,下面的行试图在 int 上使用 dict 查找 (.getitem),这显然不存在。

if len(y['paragraphs']) > 4:

【讨论】:

    【解决方案2】:

    原来需要的是:

    for y in range(3000, 3500):
        length = len(paragraphs[y])
        if length > 4:
        ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-08
      • 1970-01-01
      • 2021-05-11
      • 1970-01-01
      • 2014-07-20
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      相关资源
      最近更新 更多