Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Friday, August 9, 2019

Python: unicode chinese string recover

content = '\u6fb3\u95e8\u5927\u5b66'
content = content.encode('utf-8').decode('unicode_escape')
print (content)

# 澳门大学

Monday, August 5, 2019

Saturday, May 11, 2019

Python: sorted 2d list by element, reverse

要按第一個元素倒排, 第二個元素正排︰
sorted(lista, key=lambda x: (-x[0], x[1]))

Thursday, April 18, 2019

Python: LASER package

Used for the sentence to sentence aligner:
https://github.com/facebookresearch/LASER

Installation:
Reference the README.md

Install faiss package
conda install faiss-gpu cudatoolkit=9.0 -c pytorch


Python: environment

Create environemnt:
conda create -n NAME

Active environment:
conda activate NAME

Remove environment:
conda env remove -n NAME

Friday, March 8, 2019

Development: 2019-03

Moses tokenizer, detokenizer, truecaser port
https://github.com/alvations/sacremoses.git

pip3 install -U sacremoses

Saturday, February 16, 2019

Python: python3 from urllib import unquote cannot import name unquote

I replaced from urllib import unquote by from urllib.parse import unquote in several files and it works!

The urllib version should be tested to make the right import.

Friday, January 11, 2019

Python: pickle example

import pickle

links = []
if os.path.isfile('links.pkl'):
  all_content_links = pickle.load(open('links.pkl', 'r'))
else:
  links = fetch_links()
  pickle.dump(links , open('links.pkl', 'w'))

Monday, August 20, 2018

Pytorch: install

可以用conda進行install︰
conda install pytorch torchvision -c pytorch



Thursday, June 14, 2018

Python: loop files in directory

for filename in os.listdir(directory):
    if filename.endswith(".asm") or filename.endswith(".py"):
        # print(os.path.join(directory, filename))
        continue
    else:
        continue

Reference: How can I iterate over files in a given directory?

Friday, March 23, 2018

Python: OSError: [Errno 36] File name too long

在Python寫檔案的檔案名稱原來有長度限制,不能超過143個字符,否則就會出現錯誤。應該沒有解決方案,在寫檔案的時候小心吧。
OSError: [Errno 36] File name too long: '......'

# truncate filename if length > 100 (100 + 32 (md5) = 132 < 143 (crash limit). Later .desc is added to filename, so better 100 as max)

Reference: IOError: [Errno 36] File name too long

Wednesday, March 1, 2017

Python: 調用C++的程序

hello.h:

#include <iostream>
extern "C" {
  void display(char *msg);
}

hello.cpp:

#include "hello.h"
void display(char* msg) {
        std::cerr<<msg<<std::endl;
}

Compile:

gcc -shared hello.cpp -fPIC -o hello.so

Python:

#!/usr/bin/python
#-*- encoding:utf8 -*-
from ctypes import *
test = cdll.LoadLibrary('./hello.so')
test.display('Hello, world')


Wednesday, November 16, 2016

Python: ImportError: No module named AAA.BBB


Traceback (most recent call last):
  File "train.py", line 14, in <module>
    from AAA.BBB import
ImportError: No module named AAA.BBB

在執行Python時遇到這個問題,找不到某一個路徑下的包,原因是沒有告訴它這個文件在哪裏。
解決方案︰輸入指令export PYTHONPATH=/path/,其中path就是包含AAA.BBB文件的地方了。

Thursday, August 18, 2016

Wednesday, May 4, 2016

Python: 讀寫utf-8 文件

Python 對於讀寫中文、德文文件不能直接使用open去打開file。如果直接用open會讀到亂碼,所以可以使用codecs︰


import codecs

filein = codecs.open('filein.txt', 'r', encoding='utf-8')
fileout = codecs.open('fileout.txt', 'w', encoding='utf-8')

for line in filein:
    fileout.write(line)

filein.close()
fileout.close()

Tuesday, January 19, 2016

Python: 列表(Array)

今天被問了一個問題,在python 中 x[::-1] 是什麼? 我以為是取出最後一列,結果我猜錯了,以下就是測試。

>>> x = [1,2,3,4,5,6,7,8]
>>> print x
[1, 2, 3, 4, 5, 6, 7, 8]
>>> print x[::-1]
[8, 7, 6, 5, 4, 3, 2, 1]

原來是反向Orz..誰看得懂= =

其他測試︰

>>> x = [1,2,3,4,5,6,7,8]
>>> print x
[1, 2, 3, 4, 5, 6, 7, 8]
>>> print x[::2] #跳一個
[1, 3, 5, 7]
>>> print x[::3] #跳兩個
[1, 4, 7]
>>> print x[::-2] #反過來跳一個
[8, 6, 4, 2]
>>> print x[::-3] #反過來跳兩個
[8, 5, 2]
>>> print x[:-1] #由開始到-1
[1, 2, 3, 4, 5, 6, 7]
>>> print x[:-3] #由開始到-3
[1, 2, 3, 4, 5]
>>> print x[:3] #由開始到3
[1, 2, 3]
>>> print x[3:] #由3到最後
[4, 5, 6, 7, 8]
>>> print x[-3:] #由-3到最後
[6, 7, 8]

好吧,清晰多了。

Monday, January 18, 2016

Python: 參數分析 argparser

相比option parser來說,這個比較簡短,讀寫檔案也比較方便。


import argparse
parser = argparse.ArgumentParser()
parser.add_argument("source_input",
                    type=argparse.FileType('r'),
                    help="The source input ...")
parser.add_argument("source_output",
                    type=argparse.FileType('w'),
                    help="The source output ...")
args = parser.parse_args()

使用就是︰

for line in args.source_input:
        ...
        args.source_output.write('end \n')

args.source_input.close()
args.source_output.close()
最後記得用close!

提示信息如下,簡單明暸︰

$ python test.py
usage: test.py [-h] input output
test.py: error: too few arguments

$ python test.py -h
usage: test.py [-h] input output

positional arguments:
  source_input        The source input ...
  source_output      The source output ...

optional arguments:
  -h, --help  show this help message and exit
更多設定請看這個

Thursday, September 3, 2015

Python: Option parser

在其他程式有時會看到"-i inputfile -o outputfile"等等的參數控制,在python其實也很容易做出來的!要使用的就是optparse這個包。

簡單的官方例子︰
[root@mkytap root]# vi myProgram.py
from optparse import OptionParser
[...]
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", default=True,
                  help="don't print status messages to stdout")

(options, args) = parser.parse_args()
filename = options.filename
verbose = options.verbose

[...]

在運行時如果執行這些命令(每一行都是一樣效果)︰
[root@mkytap root]# myProgram.py --file=outfile -q
[root@mkytap root]# myProgram.py -f outfile --quiet
[root@mkytap root]# myProgram.py --quiet --file outfile
[root@mkytap root]# myProgram.py -q -f outfile
[root@mkytap root]# myProgram.py -qf outfile
程式會把outfile這個文件放到filename這個變量中,而verbose會被設定為false(預設是true)。

另外,如果執行以下命令則可以顯示使用說明(每一行都是一樣效果),格式還很好看呢~~
[root@mkytap root]# myProgram.py -h
Usage: myProgram.py [options]

Options:
  -h, --help            show this help message and exit
  -f FILE, --file=FILE  write report to FILE
  -q, --quiet           don't print status messages to stdout
[root@mkytap root]# myProgram.py --help
Usage: myProgram.py [options]

Options:
  -h, --help            show this help message and exit
  -f FILE, --file=FILE  write report to FILE
  -q, --quiet           don't print status messages to stdout

詳細的官方說明(英文)可參考: 15.5. optparse — Parser for command line options
中文的使用說明可參考: Python模块学习——optparse <=這個非常非常詳細~~想知道更多看這個吧!

Friday, August 21, 2015

Python: Python 入門

好吧..這裏就總結一下Python的教學...

首先是入門,可以看看這個圖(英中對翻)︰Python脚本直解!
這個真的很有幫助!
Reference: Python - 十分鐘入門

如果看得懂英文可以看這個說明書,有例子有圖片很詳細
Reference: TutorialsPoint
這個可以直接安裝Python 2.7.10,pip等工具︰Python: Anaconda安裝包

接下來是一個online complier(是由Python寫成的)︰CodeSkulptor
這個工具其實是在Coursera網上課程裏面的An Introduction to Interactive Programming in Python主要工具,可以使用GUI、事件控制(滑鼠或鍵盤事件)等等。這裏也有關於Python的語法總結。
如果想詳細學習這個介面工具可以看以下兩個課程︰
  1. An Introduction to Interactive Programming in Python (Part 1)
  2. An Introduction to Interactive Programming in Python (Part 2)

剩下的自己多學多用多試吧!