如何从python文本文件的字典中删除那些不属于City的关键字?

2024-10-03 17:19:47 发布

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

我有Dictionary.txt城市名称字典文件,匹配CSV文件中的城市名称,并计算每行中的匹配数。你知道吗

我对Dictionary.txt文件有个问题,它有一些不属于城市名称的关键字。所以我想从字典文件中删除所有这些不相关的关键字。我不知道怎么解决它。你知道吗

例如字典.txt是:

Nowy Dworek
Dar Bel Amri
Abaren
Hassi blal
Ambodivona
Chakla
Ippatam
Suti
Via
Zingeyskiy
Luesslingen
Bolshaya Markha
Ard Na Greine
Raskhovets
Ksizovo
Rock Elm
Batnahit

在这个文件中,我有许多不相关的关键字,例如,在一个给定的样本中via关键字不属于城市,与我的输出结果相同,如下所示您可以看到有许多不相关的关键字在描述中是匹配的

Sr_Num |    Description Cities  |matched Keywords    |Cities Total matches
1      | any description........|temple , via , Thai |3
2                                last , canada , give , on| 4
3                                this , is , on , louis |4
4                                Ocean , I , US , a , is , Southern , huge , of , this , War|   10
5                                queen  |1
6                                But , is , me , cole|  4
7                                all , Lester , Mason , is , on , us , long , of|   8
8                                Wallach , Bad , Good , Sanchez |4

那么,从dictionary.txt文件中删除不属于城市名称的所有不相关关键字的解决方案是什么???


Tags: 文件ofcsvtxt名称dictionary字典is
1条回答
网友
1楼 · 发布于 2024-10-03 17:19:47

我不会提供代码,因为我认为您可以自己完成,但以下是我的方法:

首先,把你的Dictionary.txt分成一个列表。你知道吗

然后,分割你的CSV文件,把每个城市的名字都列成一个列表。你知道吗

然后,在最后一个列表中循环检查它是否是词汇表中的单词,如果不是,则从列表中删除它。你知道吗

最后,从你得到的最终列表中重写你的CSV。你知道吗

编辑:以下是一些代码:

yourDictionnary = open('Dictionary.txt', 'r').read().splitlines() #this puts contents from the dictionnary into a list line by line
theCsvContent = ','.join(open('csvName.csv', 'r').read().splitlines()).split(',') #this puts contents from the csv into a list element by element

for index, word in enumerate(theCsvContent): #loops through theCsv with index as the word index and word as the word we're iterating on
    if word not in yourDictionnary: #checks if the word is in dictionnary and if not :
        del theCsvContent[index] #removes the word from the csv

open('result.csv', 'w').write(','.join(theCsvContent)) #this writes the edited csv into result.csv

相关问题 更多 >