[PYTHON] Senryu Judgment Program

Senryu judgment

I thought about making a Twitter bot like submitting a theme and recruiting senryu for it, so I made a program to judge senryu.

Implementation

Since there was ruby in the text analysis api of Yahoo, the number of characters in the return value was used as the number of readings.

  1. Split the string with spaces
  2. URI encoding with urllib2 respectively
  3. Send a GET request to Yahoo! api with urlopen
  4. Parse the returned XML with xmltodict and make it a dictionary
  5. Let the length of Furigana be the number of notes
  6. Judge whether it is 5 sounds, 7 sounds, or 5 sounds

senryu.py


# -*- coding: utf-8 -*-
import urllib2
import xmltodict

def yomilen(string):
  urlstr = urllib2.quote(string.encode("utf-8"))
  response = urllib2.urlopen('http://jlp.yahooapis.jp/FuriganaService/V1/furigana?appid=yourappid&sentence='+urlstr).read()
  jres = xmltodict.parse(response)
  yomigana = ""
  if isinstance(jres["ResultSet"]["Result"]["WordList"]["Word"], list):
    for result in jres["ResultSet"]["Result"]["WordList"]["Word"]:
      yomigana = yomigana + result["Furigana"]
  else:
    yomigana = jres["ResultSet"]["Result"]["WordList"]["Word"]["Furigana"]
  length = len(yomigana)
  return length

def senryu(string):
  strs = string.split(" ")
  if len(strs) == 3:
    if yomilen(strs[0]) == 5:
      if yomilen(strs[1]) == 7:
        if yomilen(strs[2]) == 5:
          print u"I'm Senryu"
          return True
        else:
          print u"The third phrase is not five notes"
          return False
      else:
        print u"The second phrase is not 7 notes"
        return False
    else:
      print u"The first phrase is not five notes"
      return False
  else:
    print u"Not 575"
    return False

Execution result

In [1]: senryu(u'If it doesn't ring, kill it. Tokitori')
I'm Senryu
Out[1]: True

Task

--The extra characters cannot be determined ――Yoon (ya, yu, yo) is also counted as one sound

Recommended Posts

Senryu Judgment Program
Multiple judgment program (not completed)