【问题标题】:Associate multiple values to one key in a dictionary Python将多个值关联到字典 Python 中的一个键
【发布时间】:2014-04-04 19:23:12
【问题描述】:

所以我正在研究这个文本挖掘项目。我正在尝试打开所有文件,获取组织和摘要的信息,在摘要中拆分单词,然后找出每个单词显示多少文件。 我的问题是关于最后一步:一个词显示多少个文件?为了回答这个问题,我正在制作一个字典 wordFrequency 来计算它。我试图告诉字典:如果字典中没有出现单词,则捕获该单词和附加的文件编号;如果字典中显示了一个单词,但文件号与任何现有的不同,则在其后面附加文件号。如果单词及其文件号都已在字典中,则忽略它。下面是我的代码。

capturedfiles = []
capturedabstracts = []
wordFrequency = {}
wordlist=open('test.txt','w')
worddict=open('test3.txt','w')
for filepath in matches[0:5]:
    with open (filepath,'rt') as mytext:
    mytext=mytext.read()
    #print mytext

    # code to capture file organizations.
    grabFile=re.findall(r'File\s+\:\s+(\w\d{7})',mytext)
    if len(grabFile) == 0:
        matchFile= "N/A"
    else:
        matchFile = grabFile[0]
    capturedfiles.append(matchFile)

    # code to capture file abstracts
    grabAbs=re.findall(r'Abstract\s\:\s\d{7}\s(\w.+)',mytext)
    if len(grabAbs) == 0:
        matchAbs= "N/A"
    else:
        matchAbs = grabAbs
    capturedabstracts.append(matchAbs)

    # arrange words in format.
    lineCount = 0
    wordCount = 0
    lines = matchAbs[0].split('. ')
    for line in lines:
        lineCount +=1
        for word in line.split(' '):
            wordCount +=1
            wordlist.write(matchFile + '|' + str(lineCount) + '|' + str(wordCount) + '|' + word + '\n')

            if word not in wordFrequency:
                wordFrequency[word]=[matchFile]
            else:
                if matchFile not in wordFrequency[word]:
                        wordFrequency[word].append(matchFile)
                worddict.write(word + '|' + str(matchFile) + '\n')


wordlist.close()
worddict.close()

我现在得到的是每个单词都打印出与其匹配的文件号。如果一个单词在整个文本中出现两次,它将分别打印两次。以下是它的外观示例:

变体|a9500006 是|a9500006 是|a9500007

我希望它看起来像:

变体|a9500006 是|a9500006, a9500007

【问题讨论】:

  • 您想要的行为正是dict 对象的工作方式,这里的问题在于您打印文本的方式。如果您只打印 dict,您应该会看到与多个值配对的键。
  • 当我尝试print wordFrequency时,它反复打印出结果。当我把它写在另一个文件中时,每个单词都被列出来了。如果一个词在一个文件或多个文件中出现多次,它们都会单独列出。
  • print wordFrequency 放在任何循环之外和代码的底部。
  • 我只是尝试输入print 语句,它会循环打印相同的结果。不能再往外移,否则会出现错误信息“unexpected indentatio”。另外,我想把它写到一个文件中,对代码有什么建议吗?谢谢。
  • "不能将它移到外面,否则会出现错误消息"unexpected indentatio"。"你试过取消缩进吗?

标签: python-2.7 dictionary


【解决方案1】:

不要每次循环写入worddict,而是在构建之后写入整个wordFrequency 字典。像这样:

#assuming wordFrequency is a correctly built dictionary
for key, value in wordFrequency.items():
    #key is a word, value is a list
    worddict.write(key + '|')
    for word in value:
        #write each word in value
        worddict.write(word)
        #if it's not the last word, write a comma
        if word != value[-1]:
            worddict.write(', ')
    #no more words, end line
    worddict.write('\n')

PS:永远不要混合制表符和空格!尤其是在 python 中!

【讨论】:

  • @Q-ximi 请解释原因,你的问题很混乱。并且看看 cmets,似乎不止我一个人这么认为。
  • 我将这段代码嵌套在 'wordFrequency[word]=[matchFile]' 下,它给了我一些非常奇怪的东西。打印出来的样子是这样|N/Aa9500003 |a9500006less|a9500006fabricated|a9500006tradeoffs|a9500006identify|a9500006(GOALI)|a9500006nominally|a9500006rapid|a9500006improvement|a9500006to|a9500006other|a9500006fuel|a9500006openings|a9500006good|a9500006crash|a9500006very|a9500006automotive|a9500006Industry|a9500006possibly|a9500006deviaitons|a9500006***
  • 你应该把代码放在最后(显然是在关闭之前)
  • 我把它放在我在帖子中尝试的地方。您能否编辑我的帖子,以便我知道我的缩进是否正确?谢谢。
  • @Q-ximi 只是按照我的方式缩进...说真的,这是基本的 Python 知识...而且不要混用制表符和空格!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-16
  • 2014-01-02
  • 1970-01-01
  • 2019-09-18
  • 1970-01-01
  • 2017-01-04
相关资源
最近更新 更多