繁体   English   中英

如何在两个 arguments function 中仅打印第一个参数?

[英]how to print only 1st argument in two arguments function?

我有一个 txt.file 和字符串输入作为 arguments,给定字符串输入我的 function 将从一组文件中打印相应的行/字符串。 文件每行一个单词。

def angram(s1,s2):
    st = set()
    if sorted(s1) == sorted(s2):
       st.add(s1)
  return st
angram('my.txt', 'top')

expected output: {'pot'}
but output I get {'pot','top'}

我不希望在集合中输入字符串。 我只想要文件中的 output 结果。 有什么办法吗??

您需要使用 Python 内置函数来读取文件。 https://www.geeksforgeeks.org/read-a-file-line-by-line-in-python/

鉴于:

car
pto
pot

Output:

{'pot', 'pto'}

代码:

def anagram(s1,s2):
    st = set()
    fh = open('my.txt')
    target = sorted(s2)
    while True:
        line = fh.readline()      # while there is line to read in the file
        check = line.strip('\n')  # some lines will include "\n" in index 0 - remove it
        if sorted(check) == target:
          st.add(check)
        if not line:
            break
    fh.close()
    st.remove(s2) # the user doesn't want the same word as the target (s2) to be included
    return st
anagram('my.txt', 'top')

暂无
暂无

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

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