Python-从文本文件访问列表中的项目

时间:2018-11-23 14:21:12

标签: python list file

我正在尝试对列表中的项目进行验证。我已经设法打开它了,但是在试图比较两个词是否是字谜的过程中却很努力。

这是我在终端机中得到的结果。

anagram:  ['word,word', 'stiff,schtiff', 'word,word', 'stiff,schtiff', 'word,word', 'stiff,schtiff', 'word,word', 'stiff,schtiff']

Anagram

在此示例中,很明显,我用两个相同的变量A,B做错了,但不确定该怎么做。

word1 = open('a.txt', 'r').read().split()
word2 = open('a.txt', 'r').read().split()
count = {}
validation = True
if len(a) == len(b):
    for i in range(len(a)):
        if a[i] in count:
            count[a[i]] += 1
        else:
            count[a[i]] = 1  
        if b[i] in count:
            count[b[i]] += 1
        else:
            count[b[i]] = 1     
    for i in count:
        if count[i] % 2 == 0:
            validation = "Anagram"
        else:
            validation = "Not Anagram"
            break
else:
    validation = "Not Anagram"            
print(validation)

我到底在做什么?

我想在终端上实现这一目标。

anagram:  ['word,word', 'stiff,schtiff', 'word,word', 'stiff,schtiff', 'word,word', 'stiff,schtiff', 'word,word', 'stiff,schtiff']

anagram, not anagram, anagram, not anagram, anagram, not anagram, anagram, not anagram

1 个答案:

答案 0 :(得分:0)

您可以尝试使用sets来实现:

anagram = ['word,word', 'stiff,schtiff', 'word,word', 'stiff,schtiff', 'word,word', 'stiff,schtiff', 'word,word', 'stiff,schtiff']
for elem in anagram:
    items = elem.split(",")
    firstLetters = set(items[0])
    secondLetters = set(items[1])
    if firstLetters == secondLetters:
        print("Anagram")
    else:
        print("Not anagram")

输出:

Anagram
Not anagram
Anagram
Not anagram
Anagram
Not anagram
Anagram
Not anagram

编辑:您可以通过以下方式从文件中读取它们并进行比较:

with open("anagram.txt","r") as inFile:
    words = [line for line in inFile]
    words = words[0].strip().split(",")
    first = []
    second = []
    for i in range(len(words)):
        if i%2 == 0:
            first.append(words[i])
        else:
            second.append(words[i])
    for f,s in zip(first,second):
        if set(f) == set(s):
            print("Anagram")
        else:
            print("Not anagram")