作者 主題: 判斷中文字串是否在 List 裡面  (閱讀 6509 次)

0 會員 與 1 訪客 正在閱讀本文。

iopklmm

  • 懷疑的國中生
  • **
  • 文章數: 71
    • 檢視個人資料
判斷中文字串是否在 List 裡面
« 於: 2013-10-05 10:35 »
請問一下

這個程式是讓使用者在命令列輸入兩個檔案,然後將這兩個檔案相同的部分印在螢幕上,但是突然發現如果這兩個檔案是英文內容可以成功,但是中文內容會失敗

我試過將檔案用UTF-8格式儲存 , 開檔也有使用 encoding=UTF-8 但是還是不行
跑出來的結果都是沒有共同行

代碼: [選擇]
import sys
f1 = open(sys.argv[1],"r",encoding="UTF-8")
f1_content = f1.readlines()

f2 = open(sys.argv[2],"r",encoding="UTF-8")
f2_content = f2.readlines()

for line in f1_content:
if line in f2_content:
print(line,end="")

f1.close()
f2.close()   

檔案1
蘋果
香蕉
鳳梨

檔案2
香蕉
奇異果
« 上次編輯: 2013-10-05 10:55 由 iopklmm »

Yamaka

  • 俺是博士!
  • *****
  • 文章數: 4913
    • 檢視個人資料
    • http://www.ecmagic.com
Re: 判斷中文字串是否在 List 裡面
« 回覆 #1 於: 2013-10-05 11:16 »
請問一下

這個程式是讓使用者在命令列輸入兩個檔案,然後將這兩個檔案相同的部分印在螢幕上,但是突然發現如果這兩個檔案是英文內容可以成功,但是中文內容會失敗

我試過將檔案用UTF-8格式儲存 , 開檔也有使用 encoding=UTF-8 但是還是不行
跑出來的結果都是沒有共同行

代碼: [選擇]
import sys
f1 = open(sys.argv[1],"r",encoding="UTF-8")
f1_content = f1.readlines()

f2 = open(sys.argv[2],"r",encoding="UTF-8")
f2_content = f2.readlines()

for line in f1_content:
if line in f2_content:
print(line,end="")

f1.close()
f2.close()   

檔案1
蘋果
香蕉
鳳梨

檔案2
香蕉
奇異果

系統環境是什麼?
下面是我跑出來的結果,環境是 ubunttu 10.04 x64

引用
$ cat file1.txt file2.txt
蘋果
香蕉
鳳梨

香蕉
奇異果
$ cat scripts/prog03.py
#!/usr/bin/env python

import sys
f1 = open(sys.argv[1],"r")
f1_content = f1.readlines()

f2 = open(sys.argv[2],"r")
f2_content = f2.readlines()

for line in f1_content:
   if line in f2_content:
      print(line)

f1.close()
f2.close()
$ scripts/prog03.py file1.txt file2.txt
香蕉

$

iopklmm

  • 懷疑的國中生
  • **
  • 文章數: 71
    • 檢視個人資料
Re: 判斷中文字串是否在 List 裡面
« 回覆 #2 於: 2013-10-05 14:14 »
竟然有結果! 我的是 windows 8 但是還是不可以...
« 上次編輯: 2013-10-05 14:20 由 iopklmm »

Yamaka

  • 俺是博士!
  • *****
  • 文章數: 4913
    • 檢視個人資料
    • http://www.ecmagic.com
Re: 判斷中文字串是否在 List 裡面
« 回覆 #3 於: 2013-10-05 19:17 »
竟然有結果! 我的是 windows 8 但是還是不可以...

應該是系統字元編碼的問題
我沒 win8,所以在 xp + python 3.1 試
在程式碼最開頭加一行

代碼: [選擇]
# -*- coding: cp950 -*-
然後 utf-8 編碼都改成一般 ascii 存檔
『encoding="UTF-8"』刪除
這樣應該就有結果顯示出來了

iopklmm

  • 懷疑的國中生
  • **
  • 文章數: 71
    • 檢視個人資料
Re: 判斷中文字串是否在 List 裡面
« 回覆 #4 於: 2013-10-05 21:37 »

恩 成功了

結果不必用 UTF-8 ....