如何比较csv文件

owfi6suc  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(76)

我想比较两个csv文件,并得到常见的种族主义单词的输出.我不想要整个解决方案,但我的问题是,我不明白它如何比较它.我不知道如何开始,希望你能帮助我.
下面是我的代码(我已经将文件重命名为example -它是一个项目)

import csv
import re
import urllib.request

import pandas as pd
from bs4 import BeautifulSoup
from nltk.tag import pos_tag
from nltk.tokenize import word_tokenize
from numpy.core.setup_common import file

url = 'https://www.afd.de/zuwanderung-asyl/'
ourUrl = urllib.request.urlopen(url)
soup = BeautifulSoup(ourUrl, 'html.parser')
print(soup.prettify)

toggle = []
for i in soup.find_all('article', {'id': 'post-113572'}):
    per_toggle = i.find('div')
    print(per_toggle)
    toggle.append(per_toggle)

    New_toggle = []
    for each in toggle:
        new_each = str(each).replace('<br/', '')
        pattern = re.compile('<.*?>')
        result = re.sub(pattern, '', new_each)
        print(result)
        New_toggle.append(result)
        df = pd.DataFrame(New_toggle)
df.to_csv('example.csv')
df = pd.read_csv('example.csv')

reader = csv.reader(open('example.csv', 'r', encoding='utf-8'), delimiter=",", quotechar='|')
New_data = []
for line in reader:
    for field in line:
        tokens = word_tokenize(field, language='german')
    posData = pos_tag(tokens)
    print(posData)
    New_data.append(posData)
    df1 = pd.DataFrame(New_data)
    df1.to_csv('ExTokenization.csv', index=False, encoding="utf-8")

    with open('ExTokenization.csv', encoding='utf-8') as infile, open('example.csv', "a",
                                                                      encoding='utf-8') as outfile:
        for line in infile:
            outfile.write("\n" + line.lower())

reader = csv.reader(open('rassismus.csv', 'r', encoding='utf-8'), delimiter=",", quotechar='|')
New_data = []
for line in reader:
    for field in line:
        tokens = word_tokenize(field, language='german')
    posData = pos_tag(tokens)
    print(posData)
    New_data.append(posData)
    df2 = pd.DataFrame(New_data)
    df2.to_csv('RassismusTokenization.csv', index=False)

这是我的全部代码。所以你可以看到我有RassismusTokenization(一个带有种族主义单词列表的csv)和ExTokenization.csv(来自一个网站的文本)。
我希望任何人都可以给予我一个提示。我想将种族主义者名单中的单词与文本进行比较,并希望得到结果:在文本中是:X种族主义词汇。种族主义词汇是:.....
谢谢大家的提示!!!

7d7tgy0s

7d7tgy0s1#

就像一个想法:你可能想找到所有的话,目前在两套的话(文本,假设它是一套的话,和你的一套定义种族主义的话)

[word for word in set_1 if word in set_2]

如果两个集合/文本都很长,可能会非常慢
如果你的pandas Dataframe 包含这些单词,你可以将它们交叉:

df1.set_index('racist_words').index.intersection(df2.set_index('text_words').index)

之前,您应该.drop_duplicates()

相关问题