Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Automatically parse the script path and create the absolute path of word.data #2

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 21 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
pinyin.py
=========

汉字转拼音,With Python


Example:

from pinyin import PinYin

test = PinYin()
test.load_word()
test.hanzi2pinyin(string='钓鱼岛是中国的')


Out:

test.hanzi2pinyin(string='钓鱼岛是中国的')
['diao', 'yu', 'dao', 'shi', 'zhong', 'guo', 'de']
test.hanzi2pinyin_split(string='钓鱼岛是中国的', split="-")
diao-yu-dao-shi-zhong-guo-de

pinyin.py
=========

汉字转拼音,With Python


Example:

from pinyin import PinYin

test = PinYin()
test.hanzi2pinyin(string='钓鱼岛是中国的')


Out:

test.hanzi2pinyin(string='钓鱼岛是中国的')
['diao', 'yu', 'dao', 'shi', 'zhong', 'guo', 'de']
test.hanzi2pinyin_split(string='钓鱼岛是中国的', split="-")
diao-yu-dao-shi-zhong-guo-de

22 changes: 12 additions & 10 deletions pinyin.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,27 @@


class PinYin(object):
def __init__(self, dict_file='word.data'):
def __init__(self):
self.word_dict = {}
self.dict_file = dict_file


def load_word(self):
if not os.path.exists(self.dict_file):
dirname, filename = os.path.split(__file__)
dict_file = os.path.join(dirname, 'word.data')
self.load_word(dict_file)

def load_word(self, dict_file):
if not os.path.exists(dict_file):
raise IOError("NotFoundFile")

with file(self.dict_file) as f_obj:
if len(self.word_dict.keys()) > 0:
print 'Dictionary already loaded'
return
with file(dict_file) as f_obj:
for f_line in f_obj.readlines():
try:
line = f_line.split(' ')
self.word_dict[line[0]] = line[1]
except:
line = f_line.split(' ')
self.word_dict[line[0]] = line[1]

f_obj.close()

def hanzi2pinyin(self, string=""):
result = []
Expand All @@ -54,7 +57,6 @@ def hanzi2pinyin_split(self, string="", split=""):

if __name__ == "__main__":
test = PinYin()
test.load_word()
string = "钓鱼岛是中国的"
print "in: %s" % string
print "out: %s" % str(test.hanzi2pinyin(string=string))
Expand Down