Advertisement
TDimovska

[СНЗ] Најсличен документ

Jan 23rd, 2022
628
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import math
  2. import re
  3.  
  4.  
  5. def get_words(doc):
  6.     """Поделба на документот на зборови. Стрингот се дели на зборови според
  7.    празните места и интерпукциските знаци
  8.  
  9.    :param doc: документ
  10.    :type doc: str
  11.    :return: множество со зборовите кои се појавуваат во дадениот документ
  12.    :rtype: set(str)
  13.    """
  14.     # подели го документот на зборови и конвертирај ги во мали букви
  15.     # па потоа стави ги во резултатот ако нивната должина е >2 и <20
  16.     words = list()
  17.     for word in re.split('\\W+', doc):
  18.         if 2 < len(word) < 20:
  19.             words.append(word.lower())
  20.     return words
  21.  
  22.  
  23. def get_vocabulary(documents):
  24.     """Враќа множество од сите зборови кои се појавуваат во документите.
  25.  
  26.    :param documents: листа со документи
  27.    :type documents: list(str)
  28.    :return: множество зборови
  29.    :rtype: set(str)
  30.    """
  31.     vocab = set()
  32.     for doc_text in documents:
  33.         words = get_words(doc_text)
  34.         words_set = set(words)
  35.         vocab.update(words_set)
  36.     return sorted(vocab)
  37.  
  38.  
  39. def cosine(v1, v2):
  40.     """Ја враќа косинусната сличност помеѓу два вектори v1 и v2.
  41.  
  42.    :param v1: вектор1
  43.    :type v1: list(float)
  44.    :param v2: вектор2
  45.    :type v2: list(float)
  46.    :return: сличност помеѓу вектор и вектор2
  47.    :rtype: float
  48.    """
  49.     sumxx, sumxy, sumyy = 0, 0, 0
  50.     for i in range(len(v1)):
  51.         x = v1[i]
  52.         y = v2[i]
  53.         sumxx += x * x
  54.         sumyy += y * y
  55.         sumxy += x * y
  56.     return sumxy / math.sqrt(sumxx * sumyy)
  57.  
  58.  
  59. def pearson(v1, v2):
  60.     """ Го враќа коефициентот на Пирсонова корелација помеѓу два вектори v1 и v2.
  61.  
  62.    :param v1: вектор1
  63.     :type v1: list(float)
  64.    :param v2: вектор2
  65.    :type v2: list(float)
  66.    :return: сличност помеѓу вектор и вектор2
  67.    :rtype: float
  68.    """
  69.     sum1 = 0
  70.     sum2 = 0
  71.     sum1Sq = 0
  72.     sum2Sq = 0
  73.     pSum = 0
  74.     n = len(v1)
  75.     for i in range(n):
  76.         x1 = v1[i]
  77.         x2 = v2[i]
  78.         sum1 += x1
  79.         sum1Sq += x1 ** 2
  80.         sum2 += x2
  81.         sum2Sq += x2 ** 2
  82.         pSum += x1 * x2
  83.     num = pSum - (sum1 * sum2 / n)
  84.     den = math.sqrt((sum1Sq - sum1 ** 2 / n) * (sum2Sq - sum2 ** 2 / n))
  85.     if den == 0: return 0
  86.     r = num / den
  87.     return r
  88.  
  89.  
  90. def calculate_document_frequencies(documents):
  91.     """Враќа речник со број на појавување на зборовите.
  92.  
  93.    :param documents: листа со документи
  94.    :type documents: list(str)
  95.    :return: речник со број на појавување на зборовите
  96.    :rtype: dict(str, int)
  97.    """
  98.     df = {}
  99.     documents_words = []
  100.     for doc_text in documents:
  101.         words = get_words(doc_text)
  102.         documents_words.append(words)
  103.         words_set = set(words)
  104.         for word in words_set:
  105.             df.setdefault(word, 0)
  106.             df[word] += 1
  107.     return df
  108.  
  109.  
  110. def calc_vector(cur_tf_idf, vocab):
  111.     """Пресметува tf-idf вектор за даден документ од дадениот вокабулар.
  112.  
  113.    :param cur_tf_idf: речник со tf-idf тежини
  114.    :type cur_tf_idf: dict(str, float)
  115.    :param vocab: множество од сите зборови кои се појавуваат во барем еден документ
  116.    :type vocab: set(str)
  117.    :return: tf-idf вектор за дадениот документ
  118.    """
  119.     vec = []
  120.     for word in vocab:
  121.         tf_idf = cur_tf_idf.get(word, 0)
  122.         vec.append(tf_idf)
  123.     return vec
  124.  
  125.  
  126. def process_document(doc, df, N, vocab):
  127.     """Пресметува tf-idf за даден документ.
  128.  
  129.    :param doc: документ
  130.    :type doc: str
  131.    :param df: речник со фреквенции на зборовите во дадениот документ
  132.    :type df: dict(str, int)
  133.    :param N: вкупен број на документи
  134.    :param vocab: множество од сите зборови кои се појавуваат во барем еден документ
  135.    :type vocab: set(str)
  136.    :return: tf-idf вектор за дадениот документ
  137.    """
  138.     if isinstance(doc, str):
  139.         words = get_words(doc)
  140.     else:
  141.         words = doc
  142.     idf = {}
  143.     for word, cdf in df.items():
  144.         idf[word] = math.log(N / cdf)
  145.     f = {}  # колку пати се јавува секој збор во овој документ
  146.     for word in words:
  147.         f.setdefault(word, 0)
  148.         f[word] += 1
  149.     max_f = max(f.values())  # колку пати се појавува најчестиот збор во овој документ
  150.     tf_idf = {}
  151.     for word, cnt in f.items():
  152.         ctf = cnt * 1.0 / max_f
  153.         tf_idf[word] = ctf * idf.get(word, 0)
  154.     vec = calc_vector(tf_idf, vocab)
  155.     return vec
  156.  
  157.  
  158. def rank_documents(doc, documents, sim_func=cosine):
  159.     """Враќа најслични документи со дадениот документ.
  160.  
  161.    :param doc: документ
  162.    :type doc: str
  163.    :param documents: листа со документи
  164.    :type documents: list(str)
  165.    :param sim_func: функција за сличност
  166.    :return: листа со најслични документи
  167.    """
  168.     df = calculate_document_frequencies(documents)
  169.     N = len(documents)
  170.     vocab = get_vocabulary(documents)
  171.     doc_vectors = []
  172.     for document in documents:
  173.         vec = process_document(document, df, N, vocab)
  174.         doc_vectors.append(vec)
  175.     query_vec = process_document(doc, df, N, vocab)
  176.     similarities = []
  177.     for i, doc_vec in enumerate(doc_vectors):
  178.         dist = sim_func(query_vec, doc_vec)
  179.         similarities.append((dist, i))
  180.     similarities.sort(reverse=True)
  181.     return similarities
  182.  
  183.  
  184. def create_dataset(documents, labels):
  185.     """Формира податочно множество со tf-idf тежини и класи, соодветно за класификација со дрва на одлука.
  186.  
  187.    :param documents: листа со документи
  188.    :type documents: list(str)
  189.    :param labels: листа со класи
  190.    :type labels: list
  191.    :return: податочно множество со tf-idf тежини и класи, речник со френвенции на појавување на зборовите,
  192.            број на документи во множеството, вокабулар од даденото множество на аборови
  193.    :rtype: list(list), dict(str, int), int, set(word)
  194.    """
  195.     dataset = []
  196.     doc_vectors = []
  197.     df = calculate_document_frequencies(documents)
  198.     N = len(documents)
  199.     vocab = get_vocabulary(documents)
  200.     for document in documents:
  201.         vec = process_document(document, df, N, vocab)
  202.         doc_vectors.append(vec)
  203.     for doc_vec, label in zip(doc_vectors, labels):
  204.         doc_vec.append(label)
  205.         dataset.append(doc_vec)
  206.     return dataset, df, N, vocab
  207.  
  208.  
  209. train_data = [
  210.     ("""What Are We Searching for on Mars?
  211. Martians terrified me growing up. I remember watching the 1996 movie Mars Attacks! and fearing that the Red Planet harbored hostile alien neighbors. Though I was only 6 at the time, I was convinced life on Mars meant little green men wielding vaporizer guns. There was a time, not so long ago, when such an assumption about Mars wouldn't have seemed so far-fetched.
  212. Like a child watching a scary movie, people freaked out after listening to "The War of the Worlds," the now-infamous 1938 radio drama that many listeners believed was a real report about an invading Martian army. Before humans left Earth, humanity's sense of what-or who-might be in our galactic neighborhood was, by today's standards, remarkably optimistic.
  213. """,
  214.      "science"),
  215.     ("""Mountains of Ice are Melting, But Don't Panic (Op-Ed)
  216. If the planet lost the entire West Antarctic ice sheet, global sea level would rise 11 feet, threatening nearly 13 million people worldwide and affecting more than $2 trillion worth of property.
  217. Ice loss from West Antarctica has been increasing nearly three times faster in the past decade than during the previous one - and much more quickly than scientists predicted.
  218. This unprecedented ice loss is occurring because warm ocean water is rising from below and melting the base of the glaciers, dumping huge volumes of additional water - the equivalent of a Mt. Everest every two years - into the ocean.
  219. """,
  220.      "science"),
  221.     ("""Some scientists think we'll find signs of aliens within our lifetimes. Here's how.
  222. Finding extraterrestrial life is the essence of science fiction. But it's not so far-fetched to predict that we might find evidence of life on a distant planet within a generation.
  223. "With new telescopes coming online within the next five or ten years, we'll really have a chance to figure out whether we're alone in the universe," says Lisa Kaltenegger, an astronomer and director of Cornell's new Institute for Pale Blue Dots, which will search for habitable planets. "For the first time in human history, we might have the capability to do this."
  224. """,
  225.      "science"),
  226.     ("""'Magic' Mushrooms in Royal Garden: What Is Fly Agaric?
  227. Hallucinogenic mushrooms are perhaps the last thing you'd expect to find growing in the Queen of England's garden.
  228. Yet a type of mushroom called Amanita muscaria — commonly known as fly agaric, or fly amanita — was found growing in the gardens of Buckingham Palace by the producers of a television show, the Associated Press reported on Friday (Dec. 12).
  229. A. muscaria is a bright red-and-white mushroom, and the fungus is psychoactive when consumed.
  230. """,
  231.      "science"),
  232.     ("""Upcoming Parks : 'Lost Corner' Finds New Life in Sandy Springs
  233. At the corner of Brandon Mill Road, where Johnson Ferry Road turns into Dalrymple Road, tucked among 24 forested acres, sits an early 20th Century farmhouse. A vestige of Sandy Springs' past, the old home has found new life as the centerpiece of Lost Forest Preserve. While the preserve isn't slated to officially debut until some time next year, the city has opened the hiking trails to the public until construction begins on the permanent parking lot (at the moment the parking lot is a mulched area). The new park space includes community garden plots, a 4,000-foot-long hiking trail and an ADA-accessible trail through the densely wooded site. For Atlantans seeking an alternate escape to serenity (or those who dig local history), it's certainly worth a visit.
  234. """,
  235.      "science"),
  236.     ("""Stargazers across the world got a treat this weekend when the Geminids meteor shower gave the best holiday displays a run for their money.
  237. The meteor shower is called the "Geminids" because they appear as though they are shooting out of the constellation of Gemini. The meteors are thought to be small pieces of an extinct comment called 3200 Phaeton, a dust cloud revolving around the sun. Phaeton is thought to have lost all of its gas and to be slowly breaking apart into small particles.
  238. Earth runs into a stream of debris from 3200 Phaethon every year in mid-December, causing a shower of meteors, which hit its peak over the weekend.
  239. """,
  240.      "science"),
  241.     ("""Envisioning a River of Air
  242. By the classification rules of the world of physics, we all know that the Earth's atmosphere is made of gas (rather than liquid, solid, or plasma). But in the world of flying it's often useful to think
  243. """,
  244.      "science"),
  245.     ("""Following Sunday's 17-7 loss to the Seattle Seahawks, the San Francisco 49ers were officially eliminated from playoff contention, and they have referee Ed Hochuli to blame. OK, so they have a lot of folks to point the finger at for their 7-7 record, but Hochuli's incorrect call is the latest and easiest scapegoat.
  246. """
  247.      , "sport"),
  248.     ("""Kobe Bryant and his teammates have an odd relationship. That makes sense: Kobe Bryant is an odd guy, and the Los Angeles Lakers are an odd team.
  249. They’re also, for the first time this season, the proud owners of a three-game winning streak. On top of that, you may have heard, Kobe Bryant passed Michael Jordan on Sunday evening to move into third place on the NBA’s all-time scoring list.
  250. """
  251.      , "sport"),
  252.     ("""The Patriots continued their divisional dominance and are close to clinching home-field advantage throughout the AFC playoffs. Meanwhile, both the Colts and Broncos again won their division titles with head-to-head wins.The Bills' upset of the Packers delivered a big blow to Green Bay's shot at clinching home-field advantage throughout the NFC playoffs. Detroit seized on the opportunity and now leads the NFC North.
  253. """
  254.      , "sport"),
  255.     ("""If you thought the Washington Redskins secondary was humbled by another scintillating performance from New Yorks Giants rookie wide receiver sensation Odell Beckham Jr., think again.In what is becoming a weekly occurrence, Beckham led NFL highlight reels on Sunday, collecting 12 catches for 143 yards and three touchdowns in Sunday's 24-13 victory against an NFC East rival.
  256. """
  257.      , "sport")
  258.     , ("""That was two touchdowns and 110 total yards for the three running backs. We break down the fantasy implications.The New England Patriots' rushing game has always been tough to handicap. Sunday, all three of the team's primary running backs put up numbers, and all in different ways, but it worked for the team, as the Patriots beat the Miami Dolphins, 41-13.
  259. """
  260.        , "sport"),
  261.     ("""General Santos (Philippines) (AFP) - Philippine boxing legend Manny Pacquiao vowed to chase Floyd Mayweather into ring submission after his US rival offered to fight him next year in a blockbuster world title face-off. "He (Mayweather) has reached a dead end. He has nowhere to run but to fight me," Pacquiao told AFP late Saturday, hours after the undefeated Mayweather issued the May 2 challenge on US television. The two were long-time rivals as the "best pound-for-pound" boxers of their generation, but the dream fight has never materialised to the disappointment of the boxing world.
  262. """
  263.      , "sport"),
  264.     ("""When St. John's landed Rysheed Jordan, the consensus was that he would be an excellent starter.
  265. So far, that's half true.
  266. Jordan came off the bench Sunday and tied a career high by scoring 24 points to lead No. 24 St. John's to a 74-53 rout of Fordham in the ECAC Holiday Festival.
  267. ''I thought Rysheed played with poise,'' Red Storm coach Steve Lavin said. ''Played with the right pace. Near perfect game.''
  268. """
  269.      , "sport"),
  270.     ("""Five-time world player of the year Marta scored three goals to lead Brazil to a 3-2 come-from-behind win over the U.S. women's soccer team in the International Tournament of Brasilia on Sunday. Carli Lloyd and Megan Rapinoe scored a goal each in the first 10 minutes to give the U.S. an early lead, but Marta netted in the 19th, 55th and 66th minutes to guarantee the hosts a spot in the final of the four-team competition.
  271. """
  272.      , "sport")
  273. ]
  274.  
  275. if __name__ == '__main__':
  276.     text = input()
  277.     a = [doc[0] for doc in train_data]
  278.  
  279.     rank_cos = rank_documents(text, a)
  280.     rank_pear= rank_documents(text, a, sim_func=pearson)
  281.  
  282.     c=a[rank_cos[0][1]]
  283.     p= a[rank_pear[0][1]]
  284.     print(c)
  285.     print(p)
  286.     #if(c == p):
  287.     #    print("True")
  288.     #else:
  289.     #    print("False")
  290.     print(c==p)
  291.  
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement