我有以下“greekSymbols.txt”
Α α alpha
Β β beta
Γ γ gamma
Δ δ delta
Ε ε epsilon
Ζ ζ zeta
Η η eta
Θ θ theta
Ι ι iota
Κ κ kappa
Λ λ lambda
Μ μ mu
Ν ν nu
Ξ ξ xi
Ο ο omicron
Π π pi
Ρ ρ rho
Σ σ sigma
Τ τ tau
Υ υ upsilon
Φ φ phi
Χ χ chi
Ψ ψ psi
Ω ω omega
我试图将其转换为Anki纯文本文件,并使用制表符作为分隔符。我将每行转换成两张牌,前面是符号(大写或小写),后面是名称。我有以下内容。
#!/usr/local/bin/python
import re
pattern = re.compile(r"(.)\s+(.)\s+(.+)", re.UNICODE)
input = open("./greekSymbols.txt", "r")
output = open("./greekSymbolsFormated.txt", "w+")
line = input.readline()
while line:
string = line.rstrip()
m = pattern.match(string)
if m:
output.write(m.group(1) + "\t" + m.group(3) + "\n")
output.write(m.group(2) + "\t" + m.group(3) + "\n")
else:
print("I was unable to process line '" + string + "' [" + str(m) + "]")
line = input.readline()
input.close();
output.close();
不幸的是,我目前正在获取每行的“我无法处理...”消息,其中str(m)的值为None。我做错了什么?
> localhost:Anki stephen$ python ./convertGreekSymbols.py
I was unable to process line 'Α α alpha' [None]
I was unable to process line 'Β β beta' [None]
...
答案 0 :(得分:5)
你真的不需要正则表达式:
with (open("./greekSymbols.txt") as infile,
open("./greekSymbolsFormated.txt", "w+") as outfile):
for line in infile:
up, low, name = line.split()
outfile.write("{0}\t{1}".format(up,name))
outfile.write("{0}\t{1}".format(low,name))
如果您想坚持使用正则表达式,请尝试使用以下正则表达式而不是您的正则表达式(这应该适用于IMO,但可能不够明确):
pattern = re.compile(r"(\S+)\s+(\S+)\s+(.+)", re.UNICODE)
答案 1 :(得分:2)
在我看来,这是解析错误的空白。不应该是(.)\s(.)\s(.+)
而不是\t
吗?您的输入似乎没有标签。
答案 2 :(得分:2)
你有一个没有标签的地方,应该是\ s:
>>> matcher = re.compile(r"(.)\s(.)\t(.+)", re.UNICODE)
>>> phi = "Φ φ phi"
>>> matcher.match(phi)
>>> matcher = re.compile(r"(.)\s(.)\s+(.+)", re.UNICODE)
>>> matcher.match(phi)
<_sre.SRE_Match object at 0x1018d8290>
>>>
答案 3 :(得分:0)
这是最终使事情有效的代码。看来我的原始文件是utf-8,这导致了问题。这是一个工作解决方案,允许我为Anki创建一个/ t分离的导入文件。
#!/usr/local/bin/python
import re
import codecs
pattern = re.compile(r"(\S+)\s+(\S+)\s+(.+)", re.UNICODE)
input = codecs.open("./greekSymbols.txt", "r", encoding="utf-8")
output = codecs.open("./greekSymbolsFormated.txt", "w+", encoding="utf-8")
line = input.readline()
while line:
string = line.rstrip()
m = pattern.match(string)
if m:
output.write(unicode(m.group(1) + "\t" + m.group(3) + "\n"))
output.write(unicode(m.group(2) + "\t" + m.group(3) + "\n"))
else:
print("I was unable to process line '" + string + "' [" + str(m) + "]")
line = input.readline()
input.close();
output.close();