简体   繁体   English

从python文件读取

[英]Reading from a python file

I have a text file that got some antonyms in the format: 我有一个文本文件,其中包含一些反义词,格式为:

able || 能够|| unable 无法
unable || 无法|| able 能够
abaxial || 背面|| adaxial 正面
adaxial || 正面|| abaxial 背面

and I need to check if this word is antonyms of another or not. 我需要检查这个词是否是另一个的反义词。

What i did is a code like this: 我所做的是这样的代码:

def antonyms():
    f = open('antonyms.txt', 'r+')
    for line in f:
        a = line.split('||')
        x = a[0]
        y = a[1]
    return x, y

but what I have got is only the last pairs, then I tried to indent return a bit so I did 但是我得到的只是最后一对,然后我尝试缩进一点,所以我做了

def antonyms():
    f = open('antonym_adjectives.txt', 'r+')
    for line in f:
        a = line.split('||')
        x = a[0]
        y = a[1]
        return x, y

But again I got first pairs only 但是我又只有第一对

How can I get all of the pairs? 我怎样才能得到所有的对?

and how can I do something like: 以及我该如何做:

>>> antonyms(x, y)

to tell me if they are True or False? 告诉我它们是对还是错?

Your problem is that with return you are getting out of the function. 您的问题是,使用return会退出该功能。

Instead, of x = a[0] and y = a[1] , append those values to an array, and the return that array. 取而代之的是,将x = a[0]y = a[1]值附加到数组中,然后返回该数组。

the_array = []
for line in f:
    a = line.split('||')
    the_array.append((a[0],a[1]))
return the_array

You could use yield: 您可以使用yield:

def antonyms():
    f = open('antonyms.txt', 'r+')
    for line in f:
        a = line.split('||')
        x = a[0]
        y = a[1]
        yield x, y

for a,b in antonyms():
     # rest of code here

By the way, you can assign directly to x and y: 顺便说一句,您可以直接分配给x和y:

x,y = line.split('||')

A simple check if a and b are antonyms could be: 一个简单的检查a和b是否为反义词可以是:

(a == 'un' + b) or (b == 'un' + a)

It would make more sense to write a function that gets the antonym of a given word: 编写一个获取给定单词的反义词的函数会更有意义:

def antonym(word):
    with open('antonym_adjectives.txt', 'r+') as f:
        for line in f:
            a, b = line.split('||')
            a = a.strip()
            b = b.strip()
            if a == word:
                return b
            if b == word:
                return a

You can then write antonym(x) == y to check if x and y are antonyms. 然后,您可以编写antonym(x) == y来检查xy是否为反义词。 (However this assumes each word has a single unique antonym). (但是,这假设每个单词都有一个唯一的反义词)。

This reads the file from the beginning each time. 每次从头开始读取文件。 If your list of antonyms is manageable in size it might make more sense to read it in to memory as an array or dictionary. 如果您的反义词列表的大小是可管理的,那么将其作为数组或字典读入内存可能更有意义。

If you can't assume that each word has a single unique antonym, you could turn this into a generator that will return all the antonyms for a given word. 如果不能假设每个单词都有一个唯一的反义词,则可以将其变成生成器,该生成器将返回给定单词的所有反义词。

def antonym(word):
    with open('antonym_adjectives.txt', 'r+') as f:
        for line in f:
            a, b = line.split('||')
            a = a.strip()
            b = b.strip()
            if a == word:
                yield b
            if b == word:
                yield a

Then y in antonyms(x) will tell you whether x and y are antonyms, and list(antonyms(x)) will give you the list of all the antonyms of x . 然后y in antonyms(x)会告诉您xy是否为反义词,而list(antonyms(x))会为您提供x的所有反义词的列表。

Because no answer answers BOTH your questions: 因为没有答案都回答了您的问题:

Firstly: if you return, the program will stop there. 首先:如果您返回,程序将在那里停止。 So you want to yield your antonym so the whole function becomes a generator: 因此,您想yield您的反义词,以便整个函数成为生成器:

def antonyms():
    f = open('antonyms.txt', 'r+')
    for line in f:
        a = line.split(' || ') # Think you also need surrounding spaces here.
        x = a[0]
        y = a[1]
        yield x, y

To use this function to check for is_antonym(a,b) : 要使用此函数检查is_antonym(a,b)

def is_antonym(a,b):
    for x,y in antonyms():
        if a == x and b == y:
            return True
    return False

Other answers have good tips too: 其他答案也有很好的提示:
A good replacement for instance would be: [x,y] = line.split(' || ') 例如,一个很好的替代方法是: [x,y] = line.split(' || ')

that is my code .. 那是我的代码..

def antonyms(first,second):
    f = open('text.txt', 'r')

    for line in f.readlines():
        lst = [s.strip() for s in line.split('||')]
        if lst and len(lst) == 2:
            x = lst[0]
            y = lst[1]
            if first == x and second == y:
                return True
    return False

I don't think list is a good data structure for this problem. 我认为列表不是解决此问题的良好数据结构。 After you've read all the antonym pairs into a list, you still have to search the whole list to find the antonym of a word. 在将所有反义词对读入列表后,您仍然必须搜索整个列表以查找单词的反义词。 A dict would be more efficient. 判决将更有效。

antonym = {}
with open('antonym_adjectives.txt') as infile:
    for line in infile:
       x,y = line.split('||)
       antonym[x] = y
       antonym[y] = x

Now you can just look up an antonym in the dict: 现在您可以在字典中查找一个反义词:

try:
   opposite = antonym[word]
except KeyError:
   print("%s not found" %word)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM