pip install pypinyin
import pypinyin
data=u'中文转拼音的方法'
py = pypinyin.pinyin(data, style=pypinyin.NORMAL)
ret = ''.join([i[0] for i in py])
print(ret)
写成服务的话,大概是这样:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'hello@yeshen.org'
import sys
reload(sys)
sys.setdefaultencoding('utf8')
from bottle import route, run, template, run, post, request, response, get, static_file
import sys,argparse,pypinyin
@route('/pinyin')
def html_rtc():
data = ''
with open('pinyin.html', 'r') as f:
data = f.read()
return data
@post('/pinyin')
def post_text():
data = request.json['content']
py = pypinyin.pinyin(data, style=pypinyin.NORMAL)
ret = ''.join([i[0] for i in py])
print ret
return ret
def server():
run(host='127.0.0.1', port=2022)
def local():
arg_parser = argparse.ArgumentParser(description='chinese to pinyin')
arg_parser.add_argument(
'-f',
'--file',
help='file path, [test.txt] for default',
action='store',
default='t.txt')
args = arg_parser.parse_args(sys.argv[1:])
print("file: %s" % args.file)
ret = ''
with open(args.file) as f:
for line in f:
py = pypinyin.pinyin(unicode(line.strip(), "utf-8"), style=pypinyin.NORMAL)
ret += ''.join([i[0] for i in py]) + '\n'
print(ret)
if __name__ == '__main__':
server()
DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="author" content="hello@yeshen.org">
<meta name="description" content="what makes people drawn to each other and stay in those relationships?">
<title>pin yintitle>
<style type="text/css">
body{margin: 0px;background-color: #f1f1f1;}
#text-content{ display: flex; }
#current {
flex: auto;
text-align: left;
box-shadow: none;
border: none;
box-shadow: none;
-webkit-box-shadow: none;
outline:none;
font-size: 16px;
}
#last {
padding: 8px;
color: #999;
font-size: 16px;
}
style>
<script>
var file_url = "/pinyin"
function ontextchange(){
var x=document.getElementById("current");
fetch(file_url, {
method: 'POST',
body: JSON.stringify({ "content" : x.value}),
headers: {'Content-Type': 'application/json'}
}).then(res => res.text()).then(res => {
document.getElementById("last").innerText = res;
console.log(res);
});
}
script>
head>
<body>
<div id="text-content">
<textarea id="current" rows="15" onchange="ontextchange()">textarea>
div>
<div id="last">div>
body>
html>