擅长:python、mysql、java
<p>足够简单;假设动词列表是固定的并且很小,那么使用字典和<code>for</code>循环就很容易做到这一点:</p>
<pre><code>VERBS = {
"likes": "red"
, "dislikes": "blue"
, "knows": "black"
}
def replace_verb (line):
for verb, color in VERBS.items():
if verb in line:
return "%s %s;" % (
line.replace (verb, "->")
, color
)
return line
def main ():
filename = "my_file.txt"
with open (filename, "r") as fp:
for line in fp:
print replace_verb (line)
# Allow the module to be executed directly on the command line
if __name__ == "__main__":
main ()
</code></pre>