如何从字符串列表中查找唯一对并打印到列表?

2024-09-27 00:12:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个函数,它将接受一个字符串,将整个字符串分解成一个列表(或2个,甚至可能是一个字典),我在这里真的不知道

函数需要做的是从左到右读取列表,然后在索引+1位置从左到右再次读取,然后在每次迭代中添加一个新列表

从这里开始,它需要计算这些新对中的每一个,然后只返回出现2次或更多次的对

例如:

This is Bob
This is Steve
Hi I'm John

从该列表中,它应该创建一个具有以下输出的新列表:
{This is: 2} {is Bob : 1} {Bob This : 1} {is Steve : 1} {Steve Hi : 1} {Hi I'm : 1} {I'm John : 1}

然后去掉所有的1,只留下{This is : 2}给我,因为它是唯一一个出现多次的

这是我迄今为止在代码方面所做的:

import re

##Use Regex to strip numbers, newlines, and special characters from str
def wordCleanUp(cleanUp):
    cleanUpLower = cleanUp.lower()
    wordCleanUp1 = cleanUpLower.strip()
    wordCleanUp2 = re.sub("\d+", "", wordCleanUp1)
    wordCleanUp3 = re.sub(pattern="[^\w\s]", repl="", string=wordCleanUp2)
    wordCleanUp = wordCleanUp3.split()
    return wordCleanUp

def wordPairs(fileName):
    fileContent = open(fileName, 'r')
    uniquePairStr = fileContent.split()
    uniquePairList = wordCleanUp(uniquePairStr)

def main():
    fileName = input("Enter the name of file with extension, e.g. example.txt: ")

    wordPairs(fileName)


main()

正如您所看到的,我甚至没有代码在这里进行故障排除,列出的所有内容都适用于我当前使用的所有其他函数。我唯一的问题是,我不知道如何完成wordPairs函数中的代码


Tags: 函数字符串代码re列表isdefhi
2条回答

让我们把问题简化一下。将文件读入fileContent就像您所做的那样,将其拆分为单词,去掉所有空白。现在,通过zip使用移动版本的列表来创建单词对:

pairs = zip(wordList, wordList[1:])

现在只需计算对数:

from collections import Counter
pair_count = Counter(pairs)
multiple = [(key, val) for key, val in Counter.items() if val > 1]

注意,我将单词对保留为元组;如果您想要字符串,您可以在任何时候' '.join()它们

从文本中生成Bigram并计算出现次数:

import collections

# text <- open('example.txt').read()
words = text.split()
bigrams = map(' '.join, zip(words, words[1:]))
counter = collections.Counter(bigrams)
>>> dict(counter)
{'This is': 2,
 'is Bob': 1,
 'Bob This': 1,
 'is Steve': 1,
 'Steve Hi': 1,
 "Hi I'm": 1,
 "I'm John": 1}

相关问题 更多 >

    热门问题